我是在教程看到的,但是我在 Android 11 上发现不起作用了,没有报错,但是也没有达到预期的效果
public class MainActivity extends AppCompatActivity {
NetReceiver netReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
netReceiver = new NetReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.CONNECTIVITY_CHANGE");
registerReceiver(netReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(netReceiver);
}
public class NetReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"网络发生变化",Toast.LENGTH_LONG).show();
Log.e("mylog","网络发生变化");
}
}
}
我尝试在 AndroidManifest.xml 中添加权限,也是没有效果
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1
PPTing 2021-11-28 15:23:03 +08:00 1
intentFilter.addAction("android.net.CONNECTIVITY_CHANGE");
addAction() 方法里传入的应该是「 android.net.ConnectivityManager#CONNECTIVITY_ACTION 」对应的常量「"android.net.conn.CONNECTIVITY_CHANGE"」 |
3
stardust21 2021-11-28 22:10:23 +08:00
新版本推荐使用 ConnectivityManager 来监听,官方文档: https://developer.android.google.cn/training/basics/network-ops/reading-network-state
|