標籤:mystra android 網路狀態
Android手機同時支援WIFI和3G, 判斷網路連接, 判斷網路類型(WIFI或3G).
許可權:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
判斷網路連接
/** * 判斷網路是否可用, 在使用網路請求是預先使用此方法進行檢查, 以節省資源. * * @return 可用狀態 */ public static boolean isNetAvailable() { Context context = App.getAppContext(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); return (info != null && info.isAvailable() && info.isConnected()); }
判斷網路類型
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);// 3GState mobile = conMan.getNetworkInfo(0).getState();// WIFIState wifi = conMan.getNetworkInfo(1).getState();if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) { // TODO: in mobile do something} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) { // TODO: in wifi do something}
更加精細的網路類型:
TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android - 判斷網路狀態