Android:java.lang.SecurityException: Not allowed to change Do Not Disturb state

来源:互联网 发布:棒球手套知乎 编辑:程序博客网 时间:2024/05/23 17:05

在开发过程中,需要在某个时间段将手机设为静音状态,于是乎,直接写出如下代码:

if(在某个时间范围内){    setSystemSilent();}    private void setSystemSilent() {        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);    }

运行程序,就会出现标题的错误,经过网上查询,得到如下结论,缺少权限,需要加上如下权限:

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

ok,在AndroidManife中直接加上这个权限。
再次运行程序,还是出现同样的错误。郁闷了。再去网上寻找答案。
https://stackoverflow.com/questions/39151453/in-android-7-api-level-24-my-app-is-not-allowed-to-mute-phone-set-ringer-mode/39929910#39929910

这里给出了方案。添加如下代码

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N                && !mNotificationManager.isNotificationPolicyAccessGranted()) {            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);            mContext.startActivity(intent);        }

如果应用没有获取权限,会跳转到Setting下Dnd的权限申请界面。对需要该权限的应用,将开关打开。那么应用就可以正常运行,并将设备进行静音了。
下图是控制应用权限界面:
这里写图片描述

后来经过跟代码,发现在Android的源码中有相关的说明。

frameworks/base/media/java/android/media/AudioManager.java    /**     * Sets the ringer mode.     * <p>     * Silent mode will mute the volume and will not vibrate. Vibrate mode will     * mute the volume and vibrate. Normal mode will be audible and may vibrate     * according to user settings.     * <p>This method has no effect if the device implements a fixed volume policy     * as indicated by {@link #isVolumeFixed()}.     * * <p>From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed     * unless the app has been granted Do Not Disturb Access.     * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.     * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},     *            {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.     * @see #getRingerMode()     * @see #isVolumeFixed()     */    public void setRingerMode(int ringerMode) {        if (!isValidRingerMode(ringerMode)) {            return;        }        IAudioService service = getService();        try {            service.setRingerModeExternal(ringerMode, getContext().getOpPackageName());        } catch (RemoteException e) {            throw e.rethrowFromSystemServer();        }    }
阅读全文
0 0