简体   繁体   English

如何启用/禁用飞行模式?

[英]How to enable/disable airplane mode?

I am trying enable/disable airplane mode programmatically but the following code is not working.The app stops unexpectedly while running and I have to forceclose 我正在尝试以编程方式启用/禁用飞行模式,但以下代码无效。应用程序在运行时意外停止,我必须强制关闭

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_airplanemode);

Code to check the status of airplane mode boolean isEnabled = Settings.System.getInt( getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1; 用于检查飞行模式状态的代码boolean isEnabled = Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0)== 1;

Code to toggle 要切换的代码

    Settings.System.putInt(
              getContentResolver(),
              Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);

Reloading the intent 重新加载意图

    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", !isEnabled);
    sendBroadcast(intent);
        TextView a = new TextView(this);
        a.setText("AIRPLANE MODE : "+isEnabled);
        setContentView(a);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_airplanemode, menu);
    return true;
}

You need to do the following. 您需要执行以下操作。 Add the following to your Manifesf file 将以下内容添加到Manifesf文件中

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

And use the following lines of code in your onResume(), 并在onResume()中使用以下代码行,

Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 1);
newIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
newIntent.putExtra("state", true);
sendBroadcast(newIntent);

This should work, do not need to add context.sendBroadcast(). 这应该工作,不需要添加context.sendBroadcast()。

尝试向Androidmanifest.xml文件添加所需权限尝试添加

android.permission.WRITE_SETTINGS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM