不调用BroadcastReceiver的onReceive方法

时间:2015-10-22 22:50:35

标签: android android-broadcast localbroadcastmanager android-broadcastreceiver

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

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

1 个答案:

答案 0 :(得分:2)

你不应该致电intent.setAction()

您正在倾听行动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);
}