Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I receive a notification when the device loses network connectivity?

Tags:

android

I know you can write code through which you can determine whether the device is connected to a network.

But in my app what I want to do is get a notification if the device changes its state from 'network' to 'no network'. This would happen, for example, when the user travels into a tunnel and loses signal, etc. Or when on WiFi, the user goes out of range of the access point and no longer has access to the internet.

Does the Android API provide something where you can register a listener so that you get notified every time there is a change in network state?

I found this code and tried to use it, but it does not do anything. I don't get any notifications when the network state changes.

public class ConnectivityManager extends PhoneStateListener{

Activity activity;
public ConnectivityManager(Activity a){
    TelephonyManager telephonyManager = (TelephonyManager)a.getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(this, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    activity = a;
}

@Override
public void onDataConnectionStateChanged(int state) {
    super.onDataConnectionStateChanged(state);
    switch (state) {
    case TelephonyManager.DATA_DISCONNECTED:
        new AlertDialog.Builder(activity).
        setCancelable(false).
        setTitle("Connection Manager").
        setMessage("There is no network connection. Please connect to internet and start again.").
        setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                System.exit(0);
            }
        }).create();
        break;

    case TelephonyManager.DATA_CONNECTED:
        break;
    }
}
}

Also, I have added the appropriate permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
like image 977
anargund Avatar asked May 30 '11 19:05

anargund


People also ask

What causes network connection to disappear?

Your internet keeps cutting out because you or your internet provider need to resolve one or more issues. For example, your modem may be faulty, your router may be out of date, or you may have too many devices using too much data simultaneously. Cables may be damaged. Network congestion may slow speeds.

What does lost network connection mean?

If you hit a "Lost internet connection" error message, that means your client computer is having network issues. GoToMyPC will keep trying to re-establish the connection between your computers but we cannot predict when your internet connection will be back.

How do I find network interruptions?

The most accurate way to detect intermittent network problems is by using a continuous Network Monitoring Software, like Obkio. Obkio's Network Monitoring Solution continuously measures your network performance by sending and monitoring data packets through your network every 500ms using Network Monitoring Agents.


3 Answers

You might want to consider using a BroadcastReceiver for ConnectivityManager.CONNECTIVITY_ACTION instead. From the docs:

A change in network connectivity has occurred. A connection has either been established or lost. The NetworkInfo for the affected network is sent as an extra; it should be consulted to see what kind of connectivity event occurred.

This receiver works for both WiFi and cellular data connectivity, unlike PhoneStateListener.LISTEN_DATA_CONNECTION_STATE, which will only notify you for changes in cellular networks.

like image 127
Geobits Avatar answered Sep 28 '22 09:09

Geobits


myTelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

callStateListener = new PhoneStateListener(){
    public void onDataConnectionStateChanged(int state){
        switch(state){
        case TelephonyManager.DATA_DISCONNECTED:
            Log.i("State: ", "Offline");
            // String stateString = "Offline";
            // Toast.makeText(getApplicationContext(),
            // stateString, Toast.LENGTH_LONG).show();
            break;
        case TelephonyManager.DATA_SUSPENDED:
            Log.i("State: ", "IDLE");
            // stateString = "Idle";
            // Toast.makeText(getApplicationContext(),
            // stateString, Toast.LENGTH_LONG).show();
            break;
        }
    }       
};                      
myTelephonyManager.listen(callStateListener,
            PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); 
like image 20
Zahid Ansari Avatar answered Sep 28 '22 08:09

Zahid Ansari


The accepted answer didn't work for me (my tablet was connected to WiFi - no 3G). The following code worked for me:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("*** Action: " + intent.getAction());
        if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
            Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
        }
    }
}

and the change to AndroidManifest.xml

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

<receiver android:name=".custom.ConnectivityChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>
like image 38
Mahendra Liya Avatar answered Sep 28 '22 09:09

Mahendra Liya