【问题标题】:Sending Broadcast Receiver from IntentService to Fragment (Activity)将广播接收器从 IntentService 发送到 Fragment (Activity)
【发布时间】:2015-02-02 11:15:47
【问题描述】:

当我从 IntentService 向 Fragment (Activity) 发送广播接收器时遇到问题。

我有一个包含两种进程的应用程序:

第一个进程有 MainActivity 和 MainFragment。在这个片段中,我是这样实现的:

private void registerStickerReload() {
    mStickerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(DataFetcherService.ACTION_RELOAD_STICKER)) {
                // Some code here
            }
        }
    };
    IntentFilter intentFilter = new IntentFilter(
            DataFetcherService.ACTION_RELOAD_STICKER);
    mLocalBroadcastManager.registerReceiver(mStickerReceiver, intentFilter);
}

和:

private void unregisterStickerReload() {
    if (mLocalBroadcastManager != null) {
        mLocalBroadcastManager.unregisterReceiver(mStickerReceiver);
    }
}

我从 onStart() 注册接收器并从 onStop() 取消注册。 从第二个过程开始,我像 IntentService 一样运行 DataFetcherService 类。

我的代码在这里:

private class BasicLoader extends AsyncTask<Request, Void, Response> {
    public BasicLoader() {
    }

    @Override
    protected Response doInBackground(Request... params) {
        Request request = params[0];
        Response response = request.execute();
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(ACTION_RELOAD_STICKER);
                LocalBroadcastManager.getInstance(getApplicationContext())
                        .sendBroadcast(intent);
            }
        });
        return response;
    }

    @Override
    protected void onPostExecute(Response result) {
        super.onPostExecute(result);
    }
}

我进行了调试,LocalBroadcastManager 发送了广播,但它对 onReceive(Context, Intent) 没有任何操作。

以下是我尝试过的一些案例:

  • 删除处理程序。

  • 移除 Looper.getMainLooper()。

  • 移除 unregisterStickerReload()。

但它不起作用。

【问题讨论】:

    标签: android fragment intentservice


    【解决方案1】:

    如你所见LocalBroadcastManager类概览:

    帮助注册并向本地对象发送 Intent 广播 在您的流程中。

    因为DataFetcherService 服务在与datafetcher 不同的进程中运行,而活动MainFragment 在不同的进程中运行。这就是从doInBackground 方法发送广播时不调用onReceive 方法的原因。

    要在不同进程或应用程序之间接收和发送广播,请使用BroadcastReceiver

    【讨论】:

    • 感谢您的帮助。它现在正在工作。所以我的问题是我想让DataFetcherServiceMainFragmentLocalBroadcastManager 在不同的进程中运行。你对我有什么建议吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多