我的应用程序将铃声模式设置为静音,但使用 Android N 我得到了java.lang.SecurityException: Not allowed to change Do Not Disturb state
.
我按照这个步骤操作post https://stackoverflow.com/questions/39151453/in-android-7-api-level-24-my-app-is-not-allowed-to-mute-phone-set-ringer-mode以下代码将打开一个活动,其中包含一个切换按钮,用于启用更改铃声模式的权限。无需启用权限即可“支持”此活动。
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
问题是我想确保在尝试使用无声铃声模式功能之前已授予权限。
我添加了一个 CheckBoxPreference 来启用和禁用此铃声模式切换。因此,如果选中该复选框,我可以将铃声模式设置为静音,如果没有选中,我将不会更改铃声模式。
到目前为止,当用户单击复选框时,我设法启动此权限请求:
disableSoundCheckboxPreference.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
...
// check for Android N and start the activity mentioned above
但是,仅在授予权限的情况下启用此复选框的正确方法是什么?我想这应该与ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED
和一个听众,但我需要一些想法来实现这一点。
Thanks!
我设法解决了这个问题,并将发布答案,以防其他人需要。
在这种情况下不需要广播监听器。您只需要在用户第一次单击首选项时请求权限OnPreferenceClickListener
:
private void requestNotificationPolicyAccess() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.
ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
如果用户授予了权限,当他再次点击时,你就允许用户改变状态了CheckBox
。如果未获得许可,您将继续更新CheckBox
与“假”,也许写在它的android:summary
必须首先获得该许可。您可以通过以下方式验证:
private boolean isNotificationPolicyAccessGranted() {
NotificationManager notificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager.isNotificationPolicyAccessGranted();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)