Android 代码控制飞行模式开关 (4.2及以上版本亲测有效)

前言

由于业务需要, 需要代码控制飞行模式的开启和关闭, 百度了一圈发现, 大部分的代码都是android4.2的上面可以用, 但是对于现在的android6.0, 7.0, 8.0都不能用,  因为只有系统应用才能有这个权限.   那么问题来了, 如果我非要用代码来控制飞行模式, 怎么办呢? 猿曰: 只要智商不滑坡, 方法总比困难多.  

1.通过广播(无效,需要配置权限,但是配置的权限只有系统应用才能用)

private void setAirPlaneMode(Context context, boolean enable) {
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
    } else {
        Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
    }
    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", enable);
    context.sendBroadcast(intent);
}

 2.通过adb方式(亲测有效)

	private final static String COMMAND_AIRPLANE_ON = "settings put global airplane_mode_on 1 \n " +
			"am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true\n ";
	private final static String COMMAND_AIRPLANE_OFF = "settings put global airplane_mode_on 0 \n" +
			" am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false\n ";
	private final static String COMMAND_SU = "su";	

//设置飞行模式
	public void setAirplaneModeOn(boolean isEnable) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
			Settings.System.putInt(getContentResolver(),
					Settings.System.AIRPLANE_MODE_ON, isEnable ? 1 : 0);
			Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
			intent.putExtra("state", isEnable);
			sendBroadcast(intent);
		} else {//4.2或4.2以上
			if (isEnable){
				writeCmd(COMMAND_AIRPLANE_ON);
			}else {
				writeCmd(COMMAND_AIRPLANE_OFF);
			}
		}

	}

	//写入shell命令
	public static void writeCmd(String command){
		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();
		}
	}

 这种方式如果你是android4.2之前的版本,可以直接用,  如果是之后的版本, 那就需要用adb命令了,  那你如果要用adb命令, 你的手机就需要获取root权限(自行百度root权限获取), 当你运行到写入adb命令的代码的时候,  手机就会自动弹窗提示是否授予root权限.

发布了89 篇原创文章 · 获赞 98 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/mawei7510/article/details/100517051