只要巧用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{ } }
具体的代码如下: