【问题标题】:Android N: checking for DND state changed before updating checkbox preferenceAndroid N:在更新复选框首选项之前检查 DND 状态是否已更改
【发布时间】:2017-02-05 13:41:36
【问题描述】:

我的应用程序将铃声模式设置为静音,但在 Android N 上我得到了java.lang.SecurityException: Not allowed to change Do Not Disturb state

我按照post 中的步骤操作,以下代码将打开一个活动,其中包含一个切换按钮,用于启用更改铃声模式的权限。无需启用权限即可“支持”此活动。

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和一个听众有关,但我需要一些想法来实现它。

谢谢!

【问题讨论】:

    标签: android android-notifications android-preferences android-audiomanager android-7.0-nougat


    【解决方案1】:

    我设法解决了这个问题,并会在其他人需要时发布答案。

    在这种情况下不需要广播监听器。您只需要在用户第一次点击带有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的状态。如果未授予权限,您将继续使用“false”更新CheckBox,并可能在android:summary 中写入必须首先授予权限。您可以通过以下方式进行验证:

    private boolean isNotificationPolicyAccessGranted()  {
        NotificationManager notificationManager = (NotificationManager)
                getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        return notificationManager.isNotificationPolicyAccessGranted();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2013-10-03
      • 2017-08-16
      • 1970-01-01
      • 2012-04-02
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多