Android中检查网络连接状态的变化无网络时跳转到设置界面
时间:2021-02-18 11:19:09|栏目:Android代码|点击: 次
在AndroidManifest.xml中加一个权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter>
主代码中实现:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkNetwork(); if (!checkNetwork()) { Toast.makeText(this, "没有网络", Toast.LENGTH_LONG).show(); Intent intent = new Intent("android.settings.WIRELESS_SETTINGS"); startActivity(intent); return; } } private boolean checkNetwork() { ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo net = conn.getActiveNetworkInfo(); if (net != null && net.isConnected()) { return true; } return false; }