Search code examples
androidandroid-broadcastlocalbroadcastmanagerandroid-broadcastreceiver

BroadcastReceiver's onReceive method is not called


I have an Activity with Fragment inside and IntentService. When I click button dialog fragment opens and I enter my data. After that I click Ok and it calls getActivity().startService(intent). Service calls sendBroadcast(intent) through LocalBroadcastManager, but onReceive() method is not being called. What's wrong? There's my 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;
        }
    }
};

I register receiver here

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

my onDestroy method

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

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

and my method in service which sends broadcast

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

Solution

  • You should not call intent.setAction().

    You are listening for Intents with action ApiService.API_BROADCAST:

    • When registering, you use new IntentFilter(ApiService.API_BROADCAST);
    • When broadcasting, you use new Intent(ApiService.API_BROADCAST);

    That is OK, but if you later call intent.setAction("register"), you are overriding the first action you set.

    Instead, try passing the sub-action string as an 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);
    }