Android中檢查網路連線狀態的變化,無網路時跳轉到設定介面
阿新 • • 發佈:2019-01-28
在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; }