Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1531881
  • 博文数量: 113
  • 博客积分: 3526
  • 博客等级: 中校
  • 技术积分: 1815
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-08 09:46
个人简介

记录总结自己的工作

文章分类

全部博文(113)

文章存档

2015年(19)

2014年(10)

2013年(6)

2012年(16)

2011年(24)

2010年(21)

2009年(17)

分类: Android平台

2014-10-27 15:45:56

        控制数据链接的开关首先要申请权限:
        由于安卓没有提供公开的api进行操作,所以要使用反射才可以完成:

点击(此处)折叠或打开

  1. private void setMobileDataEnabled(Context context, boolean enabled) {
  2.         final ConnectivityManager conman = (ConnectivityManager) context
  3.                 .getSystemService(Context.CONNECTIVITY_SERVICE);
  4.         Class conmanClass;
  5.         try {
  6.             conmanClass = Class.forName(conman.getClass().getName());
  7.             final Field iConnectivityManagerField = conmanClass
  8.                     .getDeclaredField("mService");
  9.             iConnectivityManagerField.setAccessible(true);
  10.             final Object iConnectivityManager = iConnectivityManagerField
  11.                     .get(conman);
  12.             final Class iConnectivityManagerClass = Class
  13.                     .forName(iConnectivityManager.getClass().getName());
  14.             final Method setMobileDataEnabledMethod = iConnectivityManagerClass
  15.                     .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
  16.             setMobileDataEnabledMethod.setAccessible(true);

  17.             setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
  18.         } catch (ClassNotFoundException e) {
  19.             Logger.e(TAG, e);
  20.         } catch (SecurityException e) {
  21.             Logger.e(TAG, e);
  22.         } catch (NoSuchFieldException e) {
  23.             Logger.e(TAG, e);
  24.         } catch (IllegalArgumentException e) {
  25.             Logger.e(TAG, e);
  26.         } catch (IllegalAccessException e) {
  27.             Logger.e(TAG, e);
  28.         } catch (NoSuchMethodException e) {
  29.             Logger.e(TAG, e);
  30.         } catch (InvocationTargetException e) {
  31.             Logger.e(TAG, e);
  32.         }
  33.     }
       
        控制wifi则需要申请权限:
        然后调用如下方法:

点击(此处)折叠或打开

  1. public void setWifi(boolean isEnable) {
  2.         if (mWm == null) {
  3.             mWm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
  4.         }
  5.         if (isEnable) {
  6.             if (!mWm.isWifiEnabled()) {
  7.                 mWm.setWifiEnabled(true);
  8.             }
  9.         } else {
  10.             if (mWm.isWifiEnabled()) {
  11.                 mWm.setWifiEnabled(false);
  12.             }
  13.         }
  14.     }



阅读(2399) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~