在root環(huán)境下使用shell命令調(diào)用飛行模式
- 1.聲明需要使用的shell命令
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";
- 2.執(zhí)行命令的方法
/****
* 寫入shell命令
* @param command
*/
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();
}
}
- 3.設(shè)置飛行模式
/**
*設(shè)置飛行模式
* @param isEnable true 開啟 false 關(guān)閉
*/
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) {
new Thread(new Runnable() {
@Override
public void run() {
writeCmd(COMMAND_AIRPLANE_ON);
}
}).start();
} else {
new Thread(new Runnable() {
@Override
public void run() {
writeCmd(COMMAND_AIRPLANE_OFF);
}
}).start();
}
}
}
4.使用控件設(shè)置飛行模式
mBtnAir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAirFlyingFlag) {
setAirplaneModeOn(false);//關(guān)閉
mAirFlyingFlag=false;
mBtnAir.setText("飛行模式:關(guān)");
} else {
setAirplaneModeOn(true);//開啟
mAirFlyingFlag=true;
mBtnAir.setText("飛行模式:開");
}
}
});
使用魅族手機(jī)6.0的時候遇到個問題改橘。使用shell命令更改飛行模式。獲取當(dāng)前是否開啟飛行模式的時候會一直返回錯誤狀態(tài)(使用shell命令前的狀態(tài))践樱。所以狀態(tài)標(biāo)識使用自己的mAirFlyingFlag判斷。
判斷方法
/****
* 獲取飛行模式狀態(tài)
* @return
*/
public static boolean IsAirModeOn(Context context) {
return (Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1 ? true : false);
}
注意:必須在root環(huán)境才能使用