Android判断上网方式(Wifi还是数据流量)
16lz
2021-01-23
首先要在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) { //WIFI return info.isConnected(); } else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) { //MOBILE return 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; else return 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 按钮效果的两种实现方法
- Android前端开发15:显示网络图片
- Android设置桌面背景图片的方法
- Android 4.0 使用网络 NetworkOnMainThreadException
- [置顶] 找到一个在Android上创建阻塞式模态对话框的方法
- Android来电拦截的实现方法
- Android实现文件保存数据,读取数据