GJain
GJain

Reputation: 5093

android Connectivity_Change broadcastreceiver not getting called consistently

I am trying to test/implement lost network use case. I have code as mentioned below.

I run it on Galaxy S6. I have both mobile data and wifi enabled.

To disable network, I turn on "Airplane Mode"

My issue is:

If I relaunch app from android studio, I do get ConnectionChangeReceiver.onReceive() called. However, after few turn on/off Airplane mode, I do not get onReceive() called.

I set breakpoint in studio to check if its called or not.

Am I missing something?

public class ConnectionChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive( Context context, Intent intent )
    {
        // get Connectivity Manager object to check connection
        ConnectivityManager connectivityManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        // Check for network connections
        if ( activeNetInfo != null && activeNetInfo.isConnected()) {
            Intent newintent = new Intent(BroadcastedIntentFilters.INTERNET_CONNECTED);
            LocalBroadcastManager.getInstance(context).sendBroadcast(newintent);
        }
    }
}

In manifest file

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


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

Upvotes: 0

Views: 1411

Answers (2)

John smith
John smith

Reputation: 1785

i find some links for that task: no. 1 no. 2

hope fully works. enjoy your code time:)

Upvotes: 0

klimat
klimat

Reputation: 24991

In Android 5.0 and higher you have to monitor changes by connectivityManager.registerNetworkCallback which is different in comparison to earlier versions where you should listen in BroadcastReveiver.

I wrote a simple class which supports all Android versions and allows monitoring changes and ask about current state as well.

https://github.com/mklimek/network-availability

Upvotes: 7

Related Questions