前言
由於業務需要, 需要代碼控制飛行模式的開啓和關閉, 百度了一圈發現, 大部分的代碼都是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權限.