我正在使用意图服务与服务器通信以获取应用程序的数据。我希望应用程序等到它请求的数据被发回(希望意味着请求数据的 IntentService 已完成运行),然后应用程序尝试访问或使用要存储数据的变量. 我该怎么做呢?谢谢!
问问题
7097 次
1 回答
8
最简单的方法是让您在从服务器收集数据后IntentService
发送一个Broadcast
,您可以在您的 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!
*/
...
}
}
现在最后一步是在您的 Activity 中注册 BroadcastReceiver:
IntentFilter statusIntentFilter = new IntentFilter(
Constants.BROADCAST_ACTION);
MyResponseReceiver responseReceiver =
new MyResponseReceiver();
// Registers the MyResponseReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
responseReceiver, statusIntentFilter );
于 2014-08-14T23:25:57.320 回答