如何等待IntentService完成其任务 [英] How to wait for an IntentService to finish its task
问题描述
我正在使用意向服务与服务器通信以获取应用程序的数据。我希望应用程序在尝试访问或使用要存储在数据中的变量之前,一直等到它所请求的数据被发送回(希望这意味着已请求数据的IntentService已完成运行)我该怎么做?
I'm using an intent service to communicate with a server to get data for an app. I'd like the app to wait until the data it requests has been sent back (hopefully meaning that the IntentService the data has been requested from has finished running) before the app attempts to access or use the variables the data is to be stored in. How would I go about doing this? thanks!
推荐答案
最简单的方法是让您的 IntentService
发送广播
完成从服务器的数据收集后,您就可以在UI线程中进行监听(例如,活动
)。
Easiest way is to have your IntentService
send a Broadcast
once it is done gathering data from the server, which you can listen to in your UI thread (e.g. 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);
}
}
然后创建您的广播接收器(单独的类或内部活动)
Then create your broadcast receiver (either a separate class or inner class within your Activity)
例如
// 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!
*/
...
}
}
现在,最后一步是在您的Activity中注册BroadcastReceiver:
Now the final step is to register the BroadcastReceiver in your Activity:
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完成其任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!