适用于所有API版本。为API <17切换authomaticaly
为API> = 17的用户操作打开飞行模式的默认活动
没有root,没有系统级权限!
在AndroidManifest.xml中添加权限:
然后:@SuppressWarnings("deprecation")
private void initAirplanemodeBtn() {
airplanemodeButton = (ToggleButton) findViewById(R.id.airplanemode_btn);
airplanemodeButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (android.os.Build.VERSION.SDK_INT
try {
// 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);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
} else {
try {
Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
try {
Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Toast.makeText(buttonView.getContext(), R.string.not_able_set_airplane, Toast.LENGTH_SHORT).show();
}
}
}
}
});
}