bge*_*hel 2 rest android android-internet intentservice android-async-http
我正在使用intent服务与服务器通信以获取应用程序的数据.在应用程序尝试访问或使用数据存储的变量之前,我希望应用程序等待它请求的数据被发回(希望意味着已请求数据的IntentService已经完成运行)我该怎么做呢?谢谢!
最简单的方法是让您的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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建您的广播接收器(您的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!
*/
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在最后一步是在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 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6140 次 |
| 最近记录: |