我正在使用Intent Service与服务器通信,以获取应用程序的数据。我希望应用程序在访问或使用存储数据的变量之前等待它请求的数据已经被发送回来(希望这意味着从中请求数据的IntentService已经完成运行)。我该如何做到这一点?谢谢!
我正在使用Intent Service与服务器通信,以获取应用程序的数据。我希望应用程序在访问或使用存储数据的变量之前等待它请求的数据已经被发送回来(希望这意味着从中请求数据的IntentService已经完成运行)。我该如何做到这一点?谢谢!
IntentService
在从服务器收集完数据后发送一个广播,然后在你的UI线程(例如Activity
)中监听这个广播。public final class Constants {
...
// Defines a custom Intent action
public static final String BROADCAST_ACTION =
"com.example.yourapp.BROADCAST";
...
// Defines the key for the status "extra" in an Intent
public static final String EXTENDED_DATA_STATUS =
"com.example.yourapp.STATUS";
...
}
public class MyIntentService extends IntentService {
@Override
protected void onHandleIntent(Intent workIntent) {
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
...
// Do work here, based on the contents of dataString
// E.g. get data from a server in your case
...
// Puts the status into the Intent
String status = "..."; // any data that you want to send back to receivers
Intent localIntent =
new Intent(Constants.BROADCAST_ACTION)
.putExtra(Constants.EXTENDED_DATA_STATUS, status);
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
// Broadcast receiver for receiving status updates from the IntentService
private class MyResponseReceiver extends BroadcastReceiver {
// Called when the BroadcastReceiver gets an Intent it's registered to receive
@
public void onReceive(Context context, Intent intent) {
...
/*
* You get notified here when your IntentService is done
* obtaining data form the server!
*/
...
}
}
IntentFilter statusIntentFilter = new IntentFilter(
Constants.BROADCAST_ACTION);
MyResponseReceiver responseReceiver =
new MyResponseReceiver();
// Registers the MyResponseReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
responseReceiver, statusIntentFilter );
IntentService
,但这并不能提供太多信息。“我的意思是我正在开发的应用程序” - 这是一个循环定义。Android开发人员编写活动、服务、内容提供程序、广播接收器以及这些组件使用的东西。在这些Android构造方面,“它”和“应用程序”是什么? - CommonsWare