1

我有一个内部有 Fragment 和 IntentService 的 Activity。当我单击按钮对话框片段打开并输入我的数据。之后,我单击 Ok 并调用 getActivity().startService(intent)。服务通过 LocalBroadcastManager 调用 sendBroadcast(intent),但未调用 onReceive() 方法。怎么了?有我的广播接收器

private BroadcastReceiver mApiBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("tag", intent.getAction());
        switch (intent.getAction()) {
            case "register":
                showMessage(intent.getStringExtra(ApiService.EXTRA_ANSWER));
                break;
            case "authorize":
                showProfile((User) intent.getParcelableExtra(ApiService.EXTRA_USER));
                break;
            default:
                break;
        }
    }
};

我在这里注册接收器

@Override
protected void onResume() {
    super.onResume();    
    LocalBroadcastManager.
        getInstance(this).
        registerReceiver(mApiBroadcastReceiver, new IntentFilter(ApiService.API_BROADCAST));
}

我的 onDestroy 方法

 @Override
protected void onPause() {
    super.onPause();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(mApiBroadcastReceiver);
}

和我在服务中发送广播的方法

private void sendMessage(Object answer) {
    Intent intent = new Intent(API_BROADCAST);
    if (answer instanceof String) {
        intent.setAction("register");
        Log.d("tag", answer.toString());
        intent.putExtra(EXTRA_ANSWER, answer.toString());

    } else if (answer instanceof User) {
        intent.setAction("authorize");
        intent.putExtra(EXTRA_USER, (User) answer);
    }
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
4

1 回答 1

2

你不应该打电话intent.setAction()

您正在收听 Intents with action ApiService.API_BROADCAST

  • 注册时,您使用new IntentFilter(ApiService.API_BROADCAST);
  • 广播时,您使用new Intent(ApiService.API_BROADCAST);

没关系,但是如果您稍后调用intent.setAction("register"),您将覆盖您设置的第一个操作。

相反,尝试将子操作字符串作为Extra

private void sendMessage(Object answer) {
    Intent intent = new Intent(API_BROADCAST);
    if (answer instanceof String) {
        intent.putExtra(EXTRA_WHAT, "register");
        intent.putExtra(EXTRA_ANSWER, answer.toString());

    } else if (answer instanceof User) {
        intent.putExtra(EXTRA_WHAT, "authorize");
        intent.putExtra(EXTRA_USER, (User) answer);
    }
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
于 2015-10-22T23:02:46.020 回答