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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…