我知道你可以编写代码来确定设备是否连接到网络。
但在我的应用程序中,我想做的是在设备将其状态从“网络”更改为“无网络”时收到通知。例如,当用户进入隧道并失去信号等时,就会发生这种情况。或者在使用 WiFi 时,用户超出接入点的范围,不再能够访问互联网。
Android API 是否提供了可以注册监听器的功能,以便在每次网络状态发生变化时收到通知?
我找到了这段代码并尝试使用它,但它什么也没做。当网络状态发生变化时,我没有收到任何通知。
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;
}
}
}
另外,我在 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>
最佳答案
您可能需要考虑为 ConnectivityManager.CONNECTIVITY_ACTION
使用 BroadcastReceiver
反而。来自文档:
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.
此接收器适用于 WiFi 和蜂窝数据连接,与 PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
不同,它只会在蜂窝网络发生变化时通知您。
关于android - 当设备失去网络连接时如何接收通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179906/