如果要用android程序來實現wifi的開啟和關閉,是一件十分簡單的事,使用WifiManager就可以實現對android wifi接口的控制,開啟和關閉wifi都是僅需要兩行代碼。但如果你想通過代碼來實現對gsm、gprs或者3G等移動網絡接口控制的話,則不是那么容易了,因為在android開發(fā)者文檔里并沒有明確的方法來實現的,通過查看android的源代碼可以知道,源代碼是通過ConnectivityManager.setMobileDataEnabled方法來實現移動網絡中的使用數據包選項的啟用和禁用的,不過android官方刻意地把這個方法隱藏了 ,是通過把方法定義為private類型來對外禁用的,也就是說只有系統(tǒng)級的應用才能調用setMobileDataEnabled方法來控制無線和網絡中的移動網絡接口。
那么對于第三方開發(fā)的android應用,是不是就沒有辦法啟用和禁用移動網絡中的使用數據包選項了?
非也!
只要巧用java中的反射就可以實現調用到ConnectivityManager類中的setMobileDataEnabled方法,從而實現用程序來啟用和禁用移動網絡中的使用數據包選項,達到開啟和關閉gprs或者3g移動網絡的目的。
具體代碼如下:
01 |
private void setMobileDataEnabled(Context context, boolean enabled) { |
02 |
final String TAG = "setMobileDataEnabled" ; |
03 |
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); |
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 ); |
14 |
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled); |
15 |
} catch (ClassNotFoundException e) { |
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" ); |