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{
}
}</pre>