Android 开发系列7 判断上网方式(Wifi还是数据流量)
生活随笔
收集整理的這篇文章主要介紹了
Android 开发系列7 判断上网方式(Wifi还是数据流量)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先要在AndroidManifest.xml加上權限:
?
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
判斷有無網絡連接:
?
?
ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mTelephony = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE); //檢查網絡連接 NetworkInfo info = mConnectivity.getActiveNetworkInfo(); if (info == null || !mConnectivity.getBackgroundDataSetting()) { return false; }
檢查網絡類型:
?
?
int netType = info.getType(); int netSubtype = info.getSubtype(); if (netType == ConnectivityManager.TYPE_WIFI) { //WIFIreturn info.isConnected(); } else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) { //MOBILEreturn info.isConnected(); } else { return false; }?
?
?
?
?
判斷WiFi是否已連接:
?
/*** make true current connect service is wifi* @param mContext* @return*/private static boolean isWifi(Context mContext) {ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {return true;}return false;}
判斷WiFi和移動流量是否已連接:
?
?
public static boolean checkNetworkConnection(Context context){final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);if(wifi.isAvailable()||mobile.isAvailable()) //getState()方法是查詢是否連接了數據網絡return true;elsereturn false;}?
?
?
?
?
只判斷移動網絡連接是否正常:
?
<span style="font-family: Arial, Helvetica, sans-serif;">public boolean isMobileConnected(Context context) { </span><span style="font-family: Arial, Helvetica, sans-serif;"> if (context != null) { </span> ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); //獲取移動網絡信息if (mMobileNetworkInfo != null) { return mMobileNetworkInfo.isAvailable(); //getState()方法是查詢是否連接了數據網絡} } return false; }?
?
?
?
?
總結
以上是生活随笔為你收集整理的Android 开发系列7 判断上网方式(Wifi还是数据流量)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: generate用法
- 下一篇: android sina oauth2.