如何在点击按钮时以编程方式启用/禁用飞行模式?我试过这个
// 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);
Run Code Online (Sandbox Code Playgroud)
但我得到错误"系统无法解析或不是一个字段",因为它需要API 16或更高版本
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Run Code Online (Sandbox Code Playgroud)
有没有任何工作方式这样做适用于所有api级别?
主要的
package com.example.tutorial;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@SuppressLint("InlinedApi")
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Global.AIRPLANE_MODE_ON, 0) != 0;
}
@SuppressLint("NewApi")
public void airplaneModeOn(View view) {
try {
android.provider.Settings.System.putInt(getContentResolver(),
Global.AIRPLANE_MODE_ON,
isAirplaneModeOn(getApplicationContext()) ? 0 : 1);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isAirplaneModeOn(getApplicationContext()));
sendBroadcast(intent);
} catch (Exception e) {
Toast.makeText(this, "Exception occured during Airplane Mode ON", Toast.LENGTH_LONG)
.show();
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Toggle"
android:onClick="airplaneModeOn" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
清单.xml
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10655 次 |
| 最近记录: |