以编程方式在Android的所有API级别上启用飞行模式 [英] Enable Airplane Mode on all API levels programmatically Android

查看:115
本文介绍了以编程方式在Android的所有API级别上启用飞行模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过单击按钮以编程方式启用/禁用飞行模式? 我已经尝试过

how to Enable/Disable Airplane Mode programmatically on onClick of a button? i have tried this

// read the airplane mode setting
  boolean isEnabled = Settings.System.getInt(
  getContentResolver(), 
  Settings.System.AIRPLANE_MODE_ON, 0) == 1;

// toggle airplane mode
Settings.System.putInt(
  getContentResolver(),
  Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);

// Post an intent to reload
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);

但是我收到错误消息系统无法解析或不是字段",因为它需要API 16或更高版本

but i get error "System cannot be resolved or is not a field" because it requires API 16 or above

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

有什么可行的方法可以在所有api级别上使用吗?

is there any working way of doing so which works on all api levels?

推荐答案

public class MainActivity extends AppCompatActivity {
private static final String TAG = "AirplaneModeActivity";
private final String COMMAND_FLIGHT_MODE_1 = "settings put global airplane_mode_on";
private final String COMMAND_FLIGHT_MODE_2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state";
ToggleButton toggleBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toggleBtn = (ToggleButton) findViewById(R.id.toggle_btn);
    toggleBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setFlightMode(MainActivity.this);


        }

        public void setFlightMode(Context context) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                // API 17 onwards.
                if (isRooted(context)) {
                    int enabled = isFlightModeEnabled(context) ? 0 : 1;
                    // Set Airplane / Flight mode using su commands.
                    String command = COMMAND_FLIGHT_MODE_1 + " " + enabled;
                    executeCommandWithoutWait(context, "-c", command);
                    command = COMMAND_FLIGHT_MODE_2 + " " + enabled;
                    executeCommandWithoutWait(context, "-c", command);
                } else {
                    try {
                        // No root permission, just show Airplane / Flight mode setting screen.
                        Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Log.e(TAG, "Setting screen not found due to: " + e.fillInStackTrace());
                    }
                }
            } else {
                // API 16 and earlier.
                boolean enabled = isFlightModeEnabled(context);
                Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enabled ? 0 : 1);
                Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
                intent.putExtra("state", !enabled);
                sendBroadcast(intent);
            }
        }

        private  boolean isRooted(Context context) {

            // get from build info
            String buildTags = android.os.Build.TAGS;
            if (buildTags != null && buildTags.contains("test-keys")) {
                return true;
            }

            // check if /system/app/Superuser.apk is present
            try {
                File file = new File("/system/app/Superuser.apk");
                if (file.exists()) {
                    return true;
                }
            } catch (Exception e1) {
                // ignore
            }

            // try executing commands
            return canExecuteCommand("/system/xbin/which su")
                    || canExecuteCommand("/system/bin/which su") || canExecuteCommand("which su");
        }

        // executes a command on the system
        private  boolean canExecuteCommand(String command) {
            boolean executedSuccesfully;
            try {
                Runtime.getRuntime().exec(command);
                executedSuccesfully = true;
            } catch (Exception e) {
                executedSuccesfully = false;
            }

            return executedSuccesfully;
        }



        @SuppressLint("NewApi")
        @SuppressWarnings("deprecation")
        private boolean isFlightModeEnabled(Context context) {
            boolean mode = false;
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                // API 17 onwards
                mode = Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
            } else {
                // API 16 and earlier.
                mode = Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
            }
            return mode;
        }

        private void executeCommandWithoutWait(Context context, String option, String command) {
            boolean success = false;
            String su = "su";
            for (int i = 0; i < 3; i++) {
                // "su" command executed successfully.
                if (success) {
                    // Stop executing alternative su commands below.
                    break;
                }
                if (i == 1) {
                    su = "/system/xbin/su";
                } else if (i == 2) {
                    su = "/system/bin/su";
                }
                try {
                    // execute command
                    Runtime.getRuntime().exec(new String[]{su, option, command});
                } catch (IOException e) {
                    Log.e(TAG, "su command has failed due to: " + e.fillInStackTrace());
                }
            }

            //boolean isEnabled = Settings.System.getInt(this.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0) == 1;
               Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, setFlightMode(context); ? 0 : 1);


        }
    });

这篇关于以编程方式在Android的所有API级别上启用飞行模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆