大家好,我是奶綠茶
如何在 Android 檢查網路是否連線,
可以使用以下程式判斷:
但這樣就只能限自行呼叫,如果想要用偵聽的話,可以寫一個 BroadcastReceiver,
同時在 intentFilter 加上 action android:name="android.net.conn.CONNECTIVITY_CHANGE"
轉載請註明出處
如何在 Android 檢查網路是否連線,
可以使用以下程式判斷:
public static boolean isNetworkAvailable( Context context ) { ConnectivityManager cm = (ConnectivityManager) context .getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (cm == null) { return false; } else { NetworkInfo[] infos = cm.getAllNetworkInfo(); if (infos != null) { for (NetworkInfo networkInfo : infos) { if(networkInfo.getState() == NetworkInfo.State.CONNECTED){ return true; } } } } return false; }
但這樣就只能限自行呼叫,如果想要用偵聽的話,可以寫一個 BroadcastReceiver,
同時在 intentFilter 加上 action android:name="android.net.conn.CONNECTIVITY_CHANGE"
public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive( Context context, Intent intent ) { boolean isNetworkAvailable = isNetworkAvailable(context); Toast.makeText(context, "isNetworkAvailable:"+isNetworkAvailable, Toast.LENGTH_LONG).show(); } public static boolean isNetworkAvailable( Context context ) { ConnectivityManager cm = (ConnectivityManager) context .getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (cm == null) { return false; } else { NetworkInfo[] infos = cm.getAllNetworkInfo(); if (infos != null) { for (NetworkInfo networkInfo : infos) { if(networkInfo.getState() == NetworkInfo.State.CONNECTED){ return true; } } } } return false; } } // 在 Manifest.xml 加上 <receiver android:name="milkmidi.demo.networkstate.ConnectionChangeReceiver" android:label="NetworkConnection"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver>
轉載請註明出處
留言