草庐IT

android - 以编程方式在所有 API 级别上启用飞行模式 Android

coder 2023-12-14 原文

如何在单击按钮时以编程方式启用/禁用飞行模式? 这个我试过了

// 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 或更高版本

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

是否有任何适用于所有 api 级别的工作方式?

最佳答案

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 级别上启用飞行模式 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23537467/

有关android - 以编程方式在所有 API 级别上启用飞行模式 Android的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  6. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  7. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  8. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  9. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  10. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

随机推荐