Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can ever the intent received by a BroadcastReceiver be null?

In other words :

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction(); // can intent==null here ?
    // could it ever throw a NPE ?
}

I need to solve this once and for all so please no ifs and buts. I would check for null but I suspect that it is not needed and therefore it is clumsy and inelegant to check. I had searched in the docs but have not found anything

EDIT : asked at google groups - see there for some interesting points

like image 931
Mr_and_Mrs_D Avatar asked Jul 08 '13 20:07

Mr_and_Mrs_D


People also ask

Which intent is used by BroadcastReceiver?

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.

How do I cancel BroadcastReceiver?

To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.

How do I check if BroadcastReceiver is registered?

Currently there is no way to check if a receiver is registered using the receiver reference. You have to unregister the receiver and catch the IllegalArgumentException that is thrown if it's not registered. This is ugly, and a boolean method to check if it's registered would be helpful.

What is intent How are they used to broadcast and receive events?

Android uses Broadcast Intents extensively to broadcast system events like battery-charging levels, network connections, and incoming calls. Broadcasting Intents is actually quite simple. Within your application component, construct the Intent you want to broadcast, and use the sendBroadcast method to send it.


1 Answers

onReceive in a BroadcastReceiver is triggered by an Intent with an action that it's registered to. So without Intent being an instance of Intent and not null, the onReceive method would never get called.

That being said, strange things can happen. I haven't looked over the code that Google wrote around broadcasts, so while in it's correct usage it would never be null, having the check is a good idea, because it's coming from code you don't control.

like image 116
bclymer Avatar answered Sep 22 '22 08:09

bclymer