Android BroadcastReceiver onReceive() called twice on android 4.0
Short answer: there isn't a difference. The BroadcastReceiver
class for both is from Android 2.3.2 r1.
I've had a similar problem, but for me it was with an HTC Desire HD with Android 2.3.5 on it - the notifications from GCM would always get received twice. I didn't manage to find the root of the problem, but there is a workaround. You can generate a unique ID for each notification in the server and send it along with the actual data. Then, in your receiver, you can update a mapping of unique ID to notification data, and if there is already data for the given ID, just ignore it.
I probably didn't make that very clear, so here's an example:
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("notificationID");
if (myMap.get(id) != null)
return;
final String action = intent.getAction();
if (action != null && action.equals(MyBroadcastReceiver.ACTION)) {
Log.d("tag", intent.getStringExtra("alert"));
myMap.put(id, *any value you need*);
}
}
If you don't need to store additional data, you can use a HashSet instead of a Map and just check if it contains the ID.
Usually onReceive is being called twice since people are registering the broadcast in 2 locations,
Most likely you are registering in your onCreate and in your onResume.
(Choose one spot to register).
Although you might have done it probably a dozen of times - it is always recommended to take another glance at the Activity Life Cycle.
I had same issue.
onReceive()
gets called twice because i was registering Broadcast receiver twice. One in my activity's onCreate()
and another in manifest
.
I remove broadcast receiver registration from onCreate()
and it's working fine. Register your broadcast receiver in only one of them.
There are two ways to do this:
- Statically in the manifest file.
- Dynamically in the code.
Which method (static or dynamic) to use when depends completely upon what you’re trying to do. Basically when you want to do some changes right on the screen (home screen, launcher, status bar, etc.) by showing up some notification or some indicator in the status bar by listening to system wide events or maybe those sent by other apps, then it make sense to use statically registered broadcast receivers. Whereas based on similar events you want to do changes right in your app when the user is using it or maybe it’s put in the background, then it makes sense to use dynamically registered receivers which’ll last till the registering components are destroyed.
For more info: http://codetheory.in/android-broadcast-receivers/