本文主要是介绍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;}//开启/关闭GPRSprivate 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;elsecommand = 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;}
这篇关于android 用代码打开 gprs(流量开关) android 5.0 ROOT的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!