我有一个需要收听网络变化的广播接收器 -
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity =
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(!noConnectivity)
{
//some stuff
}
}
};
我使用 -
注册public void startListening() {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkStateReceiver, filter);
}
我在清单中添加了以下权限 -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
当我将手机切换到飞行模式,切换wifi关闭等时,networkStateReceiver仍然没有收到任何意图。我错过了什么吗?
答案 0 :(得分:4)
请尝试使用此操作:
Intent.ACTION_AIRPLANE_MODE_CHANGED
修改强>
或者对于所有网络状态更改,请使用:
"android.intent.action.SERVICE_STATE"
答案 1 :(得分:-3)
您可以使用此功能:
首先在@Override
之前添加它private boolean isConnected = true;
private Context c;
然后使用它
//check for connectivity:
ConnectivityManager connectivityManager = (ConnectivityManager)
c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo TestConnetion = connectivityManager.getActiveNetworkInfo();
if (TestConnetion == null){
isConnected=false;
}