1.判断当前网络类型:
是否是无线连接状态:
public boolean isWifiConnected(Context context) {
ConnectivityManager connMgr
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifiNetInfo != null && wifiNetInfo.isConnected();
}
判断移动网络是否连接(在WiFi开启状态下也能检测)
public boolean isMobileConnect(Context context){
ConnectivityManager connManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class cmClass = connManager.getClass();
Class[] argClasses = null;
Object[] argObject = null;
Boolean isOpen = false;
try
{
Method method = cmClass.getMethod("getMobileDataEnabled", argClasses);
isOpen = (Boolean) method.invoke(connManager, argObject);
if(isOpen==true){
return true;
}
} catch (Exception e)
{
e.printStackTrace();
}
return false;
}
另外一种判断当前是否是移动网络类型的方法(此方法在WiFi已连接状态下无效)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
ConnectivityManager connMgr
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo.State mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
return mobile != null && mobile.isConnected;
}
下面介绍网络连接的开关:
首先看一下移动网络的开关:
// 打开或关闭移动网络连接
public void toggleMobileConnect(boolean enableMobile) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// todo
// toggleMobileConnectForLollipop(enableMobile);
return ;
}
ConnectivityManager connMgr
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class<?> cmClass = connMgr.getClass();
Class<?>[] argClasses = new Class[1];
argClasses[0] = boolean.class;
Method method;
try {
method = cmClass.getMethod("setMobileDataEnabled", argClasses);
method.invoke(connMgr, enableMobile);
} catch (Exception e) {
e.printStackTrace();
}
}
此方法在安卓5.0之前的版本是可以用的,我用的魅族5.1系统亲测无效。
无线网的开关相对来说比较简单,主要用到WifiManager,方法如下:
public void openWifi() {
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
关闭只需设为false即可。
我的第一篇博客就介绍到这里了,下次有值得分享的代码再跟大家分享。