Android实现WIFI和GPRS网络的切换
在项目的开发中因为要使用到WIFI和GPRS网络的切换,因此就研究了一下通过代码打开WIFI和GPRS的工作。
无论是切换WIFI还是切换GPRS网络都需要设置相应的权限,所以需要在AndroidManifest.xml文件中加入以下几行代码。
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
1、切换WIFI网络
public static void toggleWiFi(Context context, boolean enabled) {
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wm.setWifiEnabled(enabled);
}
2、切换GPRS网络
由于Android没有提供直接切换GPRS网络的方法,通过查看系统源码发现,系统是调用IConnectivityManager类中的setMobileDataEnabled(boolean)方法来设置GPRS网络的,由于方法不可见,只能采用反射来调用,代码如下。
public static void toggleMobileData(Context context, boolean enabled) {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class<?> conMgrClass = null; // ConnectivityManager类
Field conMgrField = null; // ConnectivityManager类中的字段
Object iConMgr = null; // IConnectivityManager类的引用
Class<?> iConMgrClass = null; // IConnectivityManager类
Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法
try {
// 取得ConnectivityManager类
conMgrClass = Class.forName(conMgr.getClass().getName());
// 取得ConnectivityManager类中的对象mService
conMgrField = conMgrClass.getDeclaredField("mService");
// 设置mService可访问
conMgrField.setAccessible(true);
// 取得mService的实例化类IConnectivityManager
iConMgr = conMgrField.get(conMgr);
// 取得IConnectivityManager类
iConMgrClass = Class.forName(iConMgr.getClass().getName());
// 取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法
setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
// 设置setMobileDataEnabled方法可访问
setMobileDataEnabledMethod.setAccessible(true);
// 调用setMobileDataEnabled方法
setMobileDataEnabledMethod.invoke(iConMgr, enabled);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
根据以上所写就可以做到WIFI网络和GPRS网络的切换了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
详解Flutter 调用 Android Native 的方法
这篇文章主要介绍了详解Flutter 调用 Android Native 的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-01-01
详解Android的Socket通信、List加载更多、Spinner下拉列表
本文主要对Android的Socket通信、List加载更多、Spinner下拉列表进行案例分析。具有很好的参考价值,需要的朋友一起来看下吧2016-12-12
安卓APP测试之使用Burp Suite实现HTTPS抓包方法
这篇文章主要介绍了安卓APP测试之使用Burp Suite实现HTTPS抓包方法,本文详解讲解了测试环境和各个软件的配置方法,需要的朋友可以参考下2015-04-04
Android自定义ImageView实现点击两张图片切换效果
这篇文章主要为大家详细介绍了Android自定义ImageView实现点击两张图片切换效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-12-12


最新评论