0

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" />
GJain
  • 5,025
  • 6
  • 48
  • 82

2 Answers2

7

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

klimat
  • 24,711
  • 7
  • 63
  • 70
  • for now, it looks like this works. I am still testing and will ask question if I see issues. – GJain May 24 '16 at 20:00
0

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

hope fully works. enjoy your code time:)

Community
  • 1
  • 1
John smith
  • 1,781
  • 17
  • 27