BroadcastReceiver receives multiple identical messages for one event

broadcast receiver not working
types of broadcast receivers in android
how to call broadcast receiver from activity in android
protected-broadcast android
broadcast receiver android
android broadcastreceiver onreceive called multiple times
broadcast message android
onreceive

I registered a receiver that listens to network events:

<receiver 
    android:label="NetworkConnection"
    android:name=".ConnectionChangeReceiver" >
    <intent-filter >
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

receiver is also very simple:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
                Log.v("@@@","Receiver : " + activeNetInfo);
        } else {
            Log.v("@@@","Receiver : " + "No network");
        }
    }
}

The problem is, when Wifi is connected I receive 3 identical messages in a row, like this:

Receiver : NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
Receiver : NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
Receiver : NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true

They are all "CONNECTED/CONNECTED" (Shouldn't they be something like CONNECTING/OBTAINING_IPADDR, etc.), so the problem is how do I tell when It's really connected? I have some routines that I want to make when wifi is actually connected, and I dont want them to be called three times in a row.

PS: 3G sends only one message, so no problem here.

Update:

Seems like it's device specific problem.

For test I took 2 Desire HD, and 4 random android phones(different Aquos models and some no-name chinese stuff). On both DHD and one random phone on wifi connect I got 3 messages, on remaining phones I got only one message. WTF.

Receiving multiple broadcast is a device specific problem. Some phones just send one broadcast while other send 2 or 3. But there is a work around:

Assuming you get the disconnect message when the wifi is disconnected, I would guess the first one is the correct one and the other 2 are just echoes for some reason.

To know that the message has been called, you could have a static boolean that gets toggled between connect and disconnect and only call your sub-routines when you receive a connection and the boolean is true. Something like:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    private static boolean firstConnect = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
            if(firstConnect) { 
                // do subroutines here
                firstConnect = false;
            }
        }
        else {
            firstConnect= true;
        }
    }
}

Broadcasts overview, Receiving multiple broadcast is a device specific problem. Some phones just send one broadcast while other send 2 or 3. But there is a work around: Assuming  Home » Android » BroadcastReceiver receives multiple identical messages for one event BroadcastReceiver receives multiple identical messages for one event Posted by: admin February 23, 2018 Leave a comment

You can also cache in a static field the last handled connection type and check against the incomming broadcasts. This way you will only get one broadcast per connection type.

When connection type gets changed it will obviously work. When device gets out of connection activeNetworkInfo will be null and currentType will be NO_CONNECTION_TYPE as in default case.

public class ConnectivityReceiver extends BroadcastReceiver {

    /** The absence of a connection type. */
    private static final int NO_CONNECTION_TYPE = -1;

    /** The last processed network type. */
    private static int sLastType = NO_CONNECTION_TYPE;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        final int currentType = activeNetworkInfo != null
                ? activeNetworkInfo.getType() : NO_CONNECTION_TYPE;

        // Avoid handling multiple broadcasts for the same connection type
        if (sLastType != currentType) {
            if (activeNetworkInfo != null) {
                boolean isConnectedOrConnecting = activeNetworkInfo.isConnectedOrConnecting();
                boolean isWiFi = ConnectivityManager.TYPE_WIFI == currentType;
                boolean isMobile = ConnectivityManager.TYPE_MOBILE == currentType;

                // TODO Connected. Do your stuff!
            } else {
                // TODO Disconnected. Do your stuff!
            }

            sLastType = currentType;
        }
}

BroadcastReceivers, create a BroadcastReceiver for receiving system events. create a the LocalBroadcastManager for sending and receiving events in the same We want to see what happens when the device receives an SMS message. We can change the IntentFilter so that the BroadcastReceiver can receive multiple types of actions. android - usage - BroadcastReceiver receives multiple identical messages for one event ordered broadcast receiver android (4) I registered a receiver that listens to network events:

In my case, I was registering my BroadcastReceivers in onResume and only unregistering them in onDestroy.

This caused each broadcastreceiver to be registered 3 or 4 times depending on how many times the activity resumes.

Setting your broadcastreceiver in the right place in terms of the activity lifecycle will allow you to stop getting multiple confusing calls.

BroadcastReceiver - Part 2, So broadcasting and intent, especially if it goes to multiple applications, can be a In fact, that's exactly what the MMS application does when an MMS message arrives. A broadcast receiver receives a broadcast, informing it that the MMS message The second does the same thing, but provides additional parameters for  56 BroadcastReceiver receives multiple identical messages for one event Dec 7 '11. 55 Meaning of the Accuracy value returned by Android GPS Jul 10 '13.

Register your LocalBroadcastreceiver in oncreate() itself not in onResume(). unregistered in onDestroy

Native Mobile Development: A Cross-Reference for iOS and Android, Message Passing Message passing is a very broad and sometimes and there are many patterns and systems that have come and gone or abided, like and “​subscribe”), event dispatchers, callbacks, observers, message queues, etc. to be received by BroadcastReceiver instances—this is the same mechanism used​  Unlike activities, android BroadcastReceiver doesn’t contain any user interface. Broadcast receiver is generally implemented to delegate the tasks to services depending on the type of intent data that’s received. Following are some of the important system wide generated intents. android.intent.action.BATTERY_LOW :

I have an application that uploads data when the user comes back online. Since my broadcast receiver can receive the intent multiple times, it can lead to the data being uploaded more than once. To handle this, I use a service that will not do anything if it is already running.

Broadcast Receiver:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    private static boolean firstConnect = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
            startService();
        }   
    }
}

Service:

public class MyService extends Service {
    private boolean mRunning;

    @Override
    public void onCreate() {
        super.onCreate();
        mRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!mRunning) {
            mRunning = true;
            uploadTheData();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

Android Broadcast Receiver: Tutorials for Beginners- 5, An example of Android Broadcast Receiver along with sample code has been Using a Broadcast Receiver, applications can register for a particular event. Notifications like incoming messages, WiFi Activated/Deactivated message The receivers with greater priority would receive the broadcast first. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed. If you register with the Application context, you receive broadcasts as long as the app is running. 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.

Braze In-App Messaging, In-App Messaging In-App Messages are great for creating unobtrusive calls to When a trigger event has more than one eligible in-app message associated with it, set a custom manager listener when an in-app message is received from Braze, Register your custom BroadcastReceiver to listen for a specific silent push  Broadcast Receivers in Xamarin.Android. 04/20/2018; 8 minutes to read +3; In this article. This section discusses how to use a Broadcast Receiver. Broadcast Receiver Overview. A broadcast receiver is an Android component that allows an application to respond to messages (an Android Intent) that are broadcast by the Android operating system or

Local Broadcast, less overhead and secure in Android, Broadcast receiver is an Android component which allows you to send or All the registered application are notified by the Android runtime once event… can also send and receives broadcast messages to and from our application. which broadcasts current date and it is received by an Activity of the same application. Android Platform. API level 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1. Manifest.permission. Manifest.permission_group. android.accessibilityservice. AccessibilityService.MagnificationController.OnMagnificationChangedListener. AccessibilityService.SoftKeyboardController.OnShowModeChangedListener.

Android BroadcastReceiver Example Tutorial, Android BroadcastReceiver, BroadcastReceiver in Android, Broadcast Receivers Android, Create and Register Broadcast Receiver, Broadcast Events, onReceiver​. the tasks to services depending on the type of intent data that's received. A Context object is also available and is used to start an activity or service using  56 BroadcastReceiver receives multiple identical messages for one event 19 Android get previous activity 16 How to hide comments and javadoc text in editor view?

Comments
  • How much time is between the logs? Can you see the currentTimeMillis() of when the events happen? I'm wondering if they are happening so closely together that the getActiveNetworkInfo() is actually returning the same object (a static object) which is being logged 3 times.
  • 17:51:50.023 17:51:50.414 17:51:50.617
  • I took your code and tried it on my phone (Samsung Galaxy S2). It was giving messages related to mobile network as well as wifi. When I turned off packet data, I only get one message each time I turn wifi on or off. It's weird that your messages are all the same though as mine were all different.
  • Hm, is see.. I'll try making clean project with only this receiver, and see what happens.
  • Wow, yeah, I it a device problem. I updated my question.
  • Thank you! This is really nice and simple idea. There are two things you need to watch for. First - store "firstConnect" somewhere, for example in shared preferences, and second is when you change from 3G to WiFi, there is no actual disconnect, so It's better to handle 3G and WiFi events separately.
  • How can you call Activity mehtods from this class? It is not initiated by the activity so I cannot send context to this class.
  • Worked on an app using this trick. It's a mess. But is the "device-specific problem" just for network broadcasts, or do arbitrary broadcasts get duplicated?
  • Thanks @Sver. That was very helpful.
  • Yes this was my case as well!