android如何用程序实现启用gprs或者3g网络

如果要用android程序来实现wifi的开启和关闭,是一件十分简单的事,使用WifiManager就可以实现对android wifi接口的控制,开启和关闭wifi都是仅需要两行代码。但如果你想通过代码来实现对gsm、gprs或者3G等移动网络接口控制的话,则不是那么容易了,因为在android开发者文档里并没有明确的方法来实现的,通过查看android的源代码可以知道,源代码是通过ConnectivityManager.setMobileDataEnabled方法来实现移动网络中的使用数据包选项的启用和禁用的,不过android官方刻意地把这个方法隐藏了 ,是通过把方法定义为private类型来对外禁用的,也就是说只有系统级的应用才能调用setMobileDataEnabled方法来控制无线和网络中的移动网络接口。



那么对于第三方开发的android应用,是不是就没有办法启用和禁用移动网络中的使用数据包选项了?



非也!



只要巧用java中的反射就可以实现调用到ConnectivityManager类中的setMobileDataEnabled方法,从而实现用程序来启用和禁用移动网络中的使用数据包选项,达到开启和关闭gprs或者3g移动网络的目的。


private void setMobileDataEnabled(Context context, boolean enabled) {
 final String TAG = "setMobileDataEnabled";
 final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 Class conmanClass;
 try {
 conmanClass = Class.forName(conman.getClass().getName());
 final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
 iConnectivityManagerField.setAccessible(true);
 final Object iConnectivityManager = iConnectivityManagerField.get(conman);
 final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
 final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
 setMobileDataEnabledMethod.setAccessible(true);

setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 Log.d(TAG, "ClassNotFoundException");
 } catch (NoSuchFieldException e) {
 Log.d(TAG, "NoSuchFieldException");
 } catch (IllegalArgumentException e) {
 Log.d(TAG, "IllegalArgumentException");
 } catch (IllegalAccessException e) {
 Log.d(TAG, "IllegalAccessException");
 } catch (NoSuchMethodException e) {
 Log.d(TAG, "NoSuchMethodException");
 } catch (InvocationTargetException e) {
 Log.d(TAG, "InvocationTargetException");
 }finally{

 }

 }






具体的代码如下:

转载于:https://my.oschina.net/netmouse/blog/184649

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值