android - 如何等待 IntentService 完成其任务

标签 android rest intentservice android-internet 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);
    }
}

然后创建您的广播接收器(在您的 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 );

关于android - 如何等待 IntentService 完成其任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25318960/

相关文章:

android - 中断 IntentService

android - 将数据从 Activity 发送到 Intentservice

java - Android ScrollView 中的 ClassCastException

android - Google Play 的特色 Android 应用对于不同地区是否有所不同?

Android Studio 2.0 Gradle 错误

java - Jersey,JAXB 并获取一个扩展抽象类的对象作为参数

java - 如何修复 1.6 中低于 1.7 的源代码级别不允许使用 '<>' 运算符?

Spring Boot Rest Controller 如何返回不同的 HTTP 状态码?

rest - 在Spring Boot API上实现JWT身份验证

Android - 当使用总线事件调用时,IntentService 在 UI 线程上运行