android - 如何在另一个 IntentService 中从一个 IntentService 接收值?

标签 android android-intent android-activity android-service android-intentservice

我有这个 IntentService (HttpService),它从 Web 服务获取原始 json 数据:

public class HttpService extends IntentService {

    public static final String BROADCAST_ACTION = "com.example.HttpService";

    public HttpService() {
        super("HttpService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        //code to get a String with jsonData


         //Then I send a broadcast
         Intent broadcastHttpResponseIntent = new Intent();
         broadcastHttpResponseIntent.setAction(BROADCAST_ACTION);
         broadcastHttpResponseIntent.putExtra("jsonData", jsonData);

         sendBroadcast(broadcastHttpResponseIntent);

    }
}

现在,从使用 HttpService 的 IntentService 中,我尝试获取广播:

public class RestaurantModel extends IntentService {

    public static final String BROADCAST_ACTION = "com.example.RestaurantModel";

    public RestaurantModel() {
        super("RestaurantModel");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.v("RestaurantModel", "onHandleIntent");

        BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.v("RestaurantModel", "onReceive");

                String jsonResponse = intent.getStringExtra("jsonData");

            }
        };

        Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
        getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
        startService(getRestaurantsJsonIntent);

        registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.BROADCAST_ACTION));
    }
}

所以我收到此错误:

RestaurantModel has leaked IntentReceiver com.example.RestaurantModel$1@42374590 that was originally registered here. Are you missing a call to unregisterReceiver()?

所以我尝试注销接收器,但似乎需要一个上下文来注销接收器。

如何从一个 IntentService 接收值到另一个 IntentService 中?

最佳答案

最好的答案是:只有一个IntentService

下一个最佳答案是:完全摆脱广播内容,并让第一个 IntentService 调用 startService() 来启动第二个 IntentService .

关于android - 如何在另一个 IntentService 中从一个 IntentService 接收值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767442/

相关文章:

android - 如何从模拟器或 pc 中的任何 android 项目获取数据库文件

android - 小部件。 Activity 泄露了 IntentReceiver

android - 来自首选项 xml 的 Mailto 可能吗?

android - 无法在模拟器/设备上运行 Android 应用程序 - Activity 不存在?

java - 创建一个子 Activity 以从列表中选择数据

android - 如何在 Android 中找到第一个 Activity ?

android - UnknownHostException 或 IllegalStateException

安卓。无需重新创建和完成即可在 2 个 Activity 之间切换

java - 在 Android 中,当应用程序首次在手机上启动时, Activity 前会出现白屏

Android:Eclipse MAT 似乎没有显示我应用程序的所有对象