Search code examples
androidbroadcastreceiver

Android BroadcastReceiver onReceive() called twice on android 4.0


I faced to one problem on android 4.0.3 (on 4.1.2 it works fine). I have in my Activity BroadcastReceiver. When I send a broadcast, method onReceive() called always twice. Please give me any suggestions about BroadcastReceiver differences on 4.0 and 4.1

private final GcmBroadcastReceiver gcmReceiver = new GcmBroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action != null && action.equals(MyBroadcastReceiver.ACTION)) {
            Log.d("tag", intent.getStringExtra("alert"));
            }
        }
    };

};


@Override
protected void onPause() {
    unregisterReceiver(gcmReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    registerGcmReceiver();
}

private void registerGcmReceiver() {
    IntentFilter filter = new IntentFilter(MyBroadcastReceiver.ACTION);
    filter.setPriority(2);
    filter.addCategory("com.android.mypackage");
    registerReceiver(gcmReceiver, filter);
}

Solution

  • 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.