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

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


接下来直接粘代码吧:

01 private void setMobileDataEnabled(Context context, booleanenabled) {
02 final String TAG = "setMobileDataEnabled";
03 final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
04 Class conmanClass;
05 try{
06 conmanClass = Class.forName(conman.getClass().getName());
07 final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
08 iConnectivityManagerField.setAccessible(true);
09 final Object iConnectivityManager = iConnectivityManagerField.get(conman);
10 final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
11 final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
12 setMobileDataEnabledMethod.setAccessible(true);
13
14 setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
15 } catch(ClassNotFoundException e) {
16 // TODO Auto-generated catch block
17 Log.d(TAG, "ClassNotFoundException");
18 } catch(NoSuchFieldException e) {
19 Log.d(TAG, "NoSuchFieldException");
20 } catch(IllegalArgumentException e) {
21 Log.d(TAG, "IllegalArgumentException");
22 } catch(IllegalAccessException e) {
23 Log.d(TAG, "IllegalAccessException");
24 } catch(NoSuchMethodException e) {
25 Log.d(TAG, "NoSuchMethodException");
26 } catch(InvocationTargetException e) {
27 Log.d(TAG, "InvocationTargetException");
28 }finally{
29
30 }
31
32 }


更多相关文章

  1. Android 网络编程---STRUTS2,JSON,HttpClient
  2. android Matrix处理图片原理及方法整理
  3. 第三部分:Android 应用程序接口指南---第二节:UI---第五章 设置(Set
  4. Android 4.4 以太网网络共享功能研究和实现
  5. Android使用VideoView播放网络视频
  6. android studio打开旧项目遇到build.gradle相关的问题解决方法
  7. android判断模拟器的三种方法

随机推荐

  1. 一文彻底搞懂Android(安卓)View的绘制流
  2. AIDL(android 接口描述语言)
  3. 用Eclipse开发和调试Android应用程序(一)
  4. Android的电源管理
  5. Android(安卓)-- 系统进程Zygote的启动分
  6. 系出名门Android(8) - 控件(View)之TextS
  7. Android实现类似excel表格的方法整理
  8. 【Android UI控件】EditText属性大全,Text
  9. android UI 之 渐变效果
  10. android 百度地图定位与覆盖物的添加,以及