javaandroidandroid-permissionsandroid-7.0-nougatsilent-notification

Auto silent android N and later


i am building an android app where i need to put the user's phone on silent mode. i am using different methods and it is working nicely up to android M(Level 23). Now as all of we know that android has updated the policy of auto silent mode in android N and later and needs special permission of Do Not Disturb Access to put phone on silent mode. I also did the same for android N and later OS releases. But it is not still working on android N and Later. When i a doing all this it doesn't give me any error but still it is not working. I am attaching the code snippets below have a look and try to figure out the issue. Thanks buddies.

Code Snippet where i am giving Do Not Disturb Access to App

public void onRingerPermissionsClicked(View view) {
    Intent intent = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
    }
    startActivity(intent);
}

Do Not Disturb Access Screenshot

Method to put phone on silent

setRingerMode(context, AudioManager.RINGER_MODE_SILENT);

Method setRingerMode()

private void setRingerMode(Context context, int mode) {
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    // Check for DND permissions for API 24+
    if (android.os.Build.VERSION.SDK_INT < 24 ||
            (android.os.Build.VERSION.SDK_INT >= 24 && !nm.isNotificationPolicyAccessGranted())) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(mode);
    }
}

Solution

  • Your way only works on API<23, after API 23 you need to use notification manager to put mobile phone on "DND mode", here's how you can do it.

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
    

    Have you added the permission for notification policy in Manifest file?? if not, then add this,

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

    you need to open separate Dialog for getting DND mode permission, which you can do by following,

    // Check if the notification policy access has been granted for the app.

    NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
         Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
         startActivity(intent);
     }