如何等待IntentService完成其任务

时间:2014-08-14 23:06:18

标签: android rest intentservice android-internet android-async-http

我使用意向服务与服务器通信以获取应用程序的数据。我希望应用程序在应用程序尝试访问或使用数据所需的变量之前等待它请求的数据被发回(希望意味着已请求数据的IntentService已经完成运行)存储在。我将如何做到这一点?谢谢!

1 个答案:

答案 0 :(得分:7)

最简单的方法是让您的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);
    }
}

然后创建您的广播接收器(您的活动中的单独的类或内部类)

E.g。

// 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 );