Search code examples
androidbroadcastreceiverbroadcastandroid-broadcastandroid-broadcastreceiver

What's wrong with my register broadcast receiver?


I have a MyBroadcastReceiver class implemented, and I tried to register one broadcast receiver in runtime with:

String MY_ACTION = "DUMMY";
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(MY_ACTION);
Log.i(TAG, "intentFilter: " + intentFilter.getAction(0));
Intent intent = context.registerReceiver(receiver, intentFilter);
Log.i(TAG, "intent returned after registering:" + intent);
Intent queryIntent = new Intent(MY_ACTION);
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(queryIntent, 0);
Log.i(TAG, "list of receivers:" + resolveInfos.toString());

I ran a broadcasting from the adb shell:

am broadcast \
-n com.foo.foo.foo/.MyBroadcastReceiver \
-a DUMMY

I also have some Log.i in my onReceive() (implemented inside MyBroadcast Receiver).

public class MyBroadcastReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
   Log.i(TAG, "in Broadcasting Receiver anyway");
   if (intent != null) {
     ...
   }
 }

}

The result is:

  • the log of intentFilter.getAction(0) gives the right action
  • the log of intent after registering gives null
  • I got empty receivers' list from log.
  • And the onReceive has never been entered(from the log I could see that)

I guess there are some errors with my register part? Any hints/advice will be hight appreciated!!


Solution

  • This code:

    Intent intent = context.registerReceiver(receiver, intentFilter);
    

    will return null because it only returns "sticky" broadcasts. This is correct, as you aren't sending a "sticky" broadcast.

    This code:

    List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(queryIntent, 0);
    

    should return an empty list because this code only returns BroadcastReceivers that have been registered in the manifest with <receiver> tags, and does NOT return anything for dynamically registered BroadcastReceivers, which your MyBroadcastReceiver is.

    I do not know why onReceive() was not called. Please post your MyBroadcastReceiver code. I don't see anything obvious. You could try this adb command instead:

    am broadcast -a DUMMY
    

    You could also try adding

    sendBroadcast(queryIntent);
    

    after this code:

    Intent queryIntent = new Intent(MY_ACTION);
    

    and see if this calls your onReceive().