安卓打开飞行模式

一、设置飞行模式代码

ContentResolver cr = getContentResolver();
if(Settings.System.getString(cr,Settings.System.AIRPLANE_MODE_ON).equals("0")){
        //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行
        //如果关闭飞行,则打开飞行
        Settings.System.putString(cr,Settings.System.AIRPLANE_MODE_ON, "1");
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        sendBroadcast(intent);
    }else{
        //否则关闭飞行
        Settings.System.putString(cr,Settings.System.AIRPLANE_MODE_ON, "0");
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        sendBroadcast(intent);
    }

二、增加权限

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

三、运行验证

运行后,APP出现crash,报错如下,为权限原因:

Permission Denial: not allowed to send broadcast android.intent.action.AIRPLAE

通过查找资料,得知在android 4.4版本之前可以使用该方法设置飞行模式,之后的安卓版本需要将在将权限编译到安卓系统里才可以生效。

四、使用SHELL命令设置

public static String AirplaneModePref1 = "settings put global airplane_mode_on ";
public static String AirplaneModePref2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state ";

public void setAirPlane(int airPlaneMode){
    String cmdPref1 = AirplaneModePref1+airPlaneMode;
    //打开飞行模式
    if(airPlaneMode == 1){
        String cmdPref2 = AirplaneModePref2+"true";
        CmdUtils.execShell(cmdPref1);
        CmdUtils.execShell(cmdPref2);
    }else{
        //关闭飞行模式
        String cmdPref2 = AirplaneModePref2+"false";
        CmdUtils.execShell(cmdPref1);
        CmdUtils.execShell(cmdPref2);
    }
}

通过验证这种方法有效。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值