android 用代码打开 gprs(流量开关) android 5.0 ROOT

在安卓5.0之前打开gprs 通常都是通过 反射调用 ConnectivityManager 的setMobileDataEnabled方法打开流量

  //检测GPRS是否打开
    private static boolean gprsIsOpenMethod(ConnectivityManager  mCM ,String methodName)
    {
        Class cmClass       = mCM.getClass();
        Class[] argClasses  = null;
        Object[] argObject  = null;

        Boolean isOpen = false;
        try
        {
            Method method = cmClass.getMethod(methodName, argClasses);

            isOpen = (Boolean) method.invoke(mCM, argObject);
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return isOpen;
    }
    //开启/关闭GPRS
    private  static void setGprsEnabled(ConnectivityManager  mCM , boolean isEnable)
    {
        Class cmClass       = mCM.getClass();
        Class[] argClasses  = new Class[1];
        argClasses[0]       = boolean.class;

        try
        {
            Method method = cmClass.getMethod("setMobileDataEnabled", argClasses);
            method.invoke(mCM, isEnable);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

android 5.0开始 加强了流量的权限管理 ,想要开启流量需要root权限

 private final static String COMMAND_L_ON = "svc data enable\n ";
    private final static String COMMAND_L_OFF = "svc data disable\n ";
    private final static String COMMAND_SU = "su";
    public static void setGprsEnabled(boolean enable,Context context){

        String command;
        if(enable)
            command = COMMAND_L_ON;
        else
            command = COMMAND_L_OFF;

        try{
            Process su = Runtime.getRuntime().exec(COMMAND_SU);
            DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

            outputStream.writeBytes(command);
            outputStream.flush();

            outputStream.writeBytes("exit\n");
            outputStream.flush();
            try {
                su.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }

            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

如果应用有root权限的话可以通过这个方式开启gprs

 public static boolean gprsEnabled(Context context,boolean bEnable)
    {
        if (Build.VERSION.SDK_INT>=21 ){
                 setGprsEnabled(bEnable,context);
        }else {

            Object[] argObjects = null;
            ConnectivityManager mCM = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            setGprsEnabled(mCM, "setMobileDataEnabled", bEnable);
        }
        return bEnable;
    }

你可能感兴趣的:(安卓)