android 无法切换闹钟和提醒权限

nnsrf1az  于 2023-05-27  发布在  Android
关注(0)|答案(1)|浏览(337)

我有一个设置闹钟的应用程序。我使用以下代码来请求用户的许可:

Intent intent = new Intent(
"android.settings.REQUEST_SCHEDULE_EXACT_ALARM",
 Uri.parse("package:"+ getPackageName())
);
 someActivityResultLauncher.launch(intent);

我在《启示录》中加入了许可:

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

当我单击启动Intent的按钮时,我可以看到:

但我不能切换按钮的权限,我不知道为什么。

dl5txlt9

dl5txlt91#

AndroidManifest.xml请求权限时,它将返回isGranted = true

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

实际上,意图是Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM

ActivityResultLauncher<Intent> startActivityForResult = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(), (ActivityResult result) -> {
            if (result.getResultCode() == RESULT_OK) {}
        });

@RequiresApi(api = Build.VERSION_CODES.S_V2)
void hasPermission(@NonNull Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2) {

        // it depends on the manifest permission, just alike the toggle does.
        if (! alarmManager.canScheduleExactAlarms()) {

        }

        // one can only disable the permission, when the manifest requested it.
        startActivityForResult.launch(new Intent(
                Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,
                Uri.parse("package:" + getPackageName())
        ));
    }
}

监听广播操作AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED
此外,还有权限USE_EXACT_ALARM,目标是API 33
参见行为变化:准确的警报许可。

相关问题