如何等待IntentService完成它的任务



我使用一个意图服务与服务器通信,以获取数据的应用程序。我希望应用程序等待,直到它请求的数据已被发送回来(希望意味着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);
    }
}

然后创建广播接收器(一个单独的类或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:

IntentFilter statusIntentFilter = new IntentFilter(
      Constants.BROADCAST_ACTION);
MyResponseReceiver responseReceiver =
      new MyResponseReceiver();
// Registers the MyResponseReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
      responseReceiver, statusIntentFilter );

相关内容

  • 没有找到相关文章

最新更新