我在这里找到了很多例子,但没有人能为我工作......我无法理解什么是错的。我需要的是在我的应用程序中输入“飞行模式”并搜索完整的例如,
我所做的是
1.请求舱单中的许可(我看过我需要“WRITE_SETTINGS”许可)
<uses-permission-sdk-m android:name="android.permission.WRITE_SETTINGS" />
2.在代码中,当我想改变飞行模式时,我会检查是否允许
private void setAirplaneMode() {
boolean permission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
permission = Settings.System.canWrite(this);
} else {
permission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED;
}
if (permission) {
//here I go to activate the airplane mode
setAirplaneModeIntent(true);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_SETTINGS)) {
//I need to explain why I want permission
//TODO
} else {
ActivityCompat.requestPermissions(this, new String[] android.Manifest.permission.WRITE_SETTINGS}, MY_PERMISSION_REQUEST_WRITE_SETTINGS);
}
}
3.我覆盖了“onRequestPermissionsResult”
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResult) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_WRITE_SETTINGS: {
if( grantResult.length > 0 &&
grantResult[0] == PackageManager.PERMISSION_GRANTED) {
setAirplaneModeIntent(true);
}
}
}
}
4.在“setAirplaneModeIntent”中我设置了飞行模式
private void setAirplaneModeIntent(boolean activateAirplaneMode) {
Settings.System.putInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
activateAirplaneMode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", activateAirplaneMode);
sendBroadcast(intent);
}
当我调试时,我输入“ActivityCompat.requestPermissions”代码但当我到达“onRequestPermissionsResult”时,结果不是PackageManager.PERMISSION_GRANTED。
怎么了?
的修改
我解决了“requestPermissions”部分。对于“WRITE_SETTINGS”权限,您需要ACTION_MANAGE_WRITE_SETTINGS意图
见这里:
无论如何,当我发送广播时,我在第4点遇到了错误
如果我没有发送广播,“Settings.System.putInt”命令似乎什么都不做
有人可以帮帮我吗?
编辑2
我投降。我发现唯一可行的方法是以这种方式打开网络设置
Intent intentAirplaneMode = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intentAirplaneMode.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentAirplaneMode);