android代码控制飞行模式开关 支持4.2以上 root

xiaoxiao2021-02-28  38

支持android 4.2以上系统 手机需要获取root权限 通过shell命令开关飞行模式 现在手机大都4.2以上了 代码可以选择性舍弃4.2一下的

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 boolean isAirplaneModeOn() { //4.2以下 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return Settings.System.getInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0; } else //4.24.2以上 { return Settings.Global.getInt(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } } //设置飞行模式 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 (enabling) 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(); } }
转载请注明原文地址: https://www.6miu.com/read-46514.html

最新回复(0)