代码控制数据流量开关

    /** 
     * 操作数据流量
     * GPRS网络开关 反射ConnectivityManager中hide的方法setMobileDataEnabled 可以开启和关闭GPRS网络 
     * @param isEnable 
     * @throws Exception 
     */  
    public static void setGprsStatus(Context context,boolean isEnable){  
        ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        Class<?> cmClass = mConnectivityManager.getClass();  
        Class<?>[] argClasses = new Class[1];  
        argClasses[0] = boolean.class;  
  
        // 反射ConnectivityManager中hide的方法setMobileDataEnabled,可以开启和关闭GPRS网络  
        Method method;
        try {
            method = cmClass.getMethod("setMobileDataEnabled", argClasses);
            method.invoke(mConnectivityManager, isEnable);  
        } catch (NoSuchMethodException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }  
    } 

这段代码可以设置GPRS的状态,用到了反射。

原文地址:https://www.cnblogs.com/tianzhijiexian/p/4251655.html