Skip to main content

Do Not Disturb

Do Not Disturb (DND) setting allows Android users to mute notifications from all (or most) applications.

There are a lot of components that make up Do Not Disturb configuration in Android, but here we will group them into 3 main components:

  1. Notification Policy Access: The permission required for our apps to manage Do Not Disturb mode.
  2. AutomaticZenRule: The class that contains the Do Not Disturb rules.
  3. ZenPolicy: The class that determines whether notifications are allowed or not to interrupt when the Do Not Disturb mode is active.

Notification Policy Access​

Requesting Notification Policy Access​

To allow our applications to acess notification policy (Do Not Disturb setting), the first thing we need to do is declare ACCESS_NOTIFICATION_POLICY permission in our AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

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

<application>
</application>

</manifest>

Then, we need to request the user to allow our applications to access notification policy by sending them to Do Not Disturb access setting page:

import android.content.Context
import android.content.Intent
import android.provider.Settings

context.startActivity(Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS))

The Do Not Disturb access setting page will look like this:

User can grant notification policy access to an app by clicking one of the apps and enable "Allow Do Not Disturb".

Checking Whether Notification Policy Access is Granted​

We can check whether our application can access Do Not Disturb settings by using isNotificationPolicyAccessGranted() method:

import android.app.NotificationManager
import android.content.Context
import android.util.Log

val notificationManager = context.getSystemService(NotificationManager::class.java)
val isGranted = notificationManager.isNotificationPolicyAccessGranted
Log.i("TAG", isGranted.toString())

Listening to Notification Policy Access Granted Changes​

We can also listen to a broadcast intent whenever our application's Do Not Disturb access changes by the user. To accomplish this, we need to create a broadcast receiver that listens to ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED intent action:

NotificationPolicyAccessGrantedChangedBroadcastListener.kt
package com.hanmajid.androidnotebook

import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

/**
* Simple broadcast receiver that listens to
* [NotificationManager.ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED] intent action.
*/
class NotificationPolicyAccessGrantedChangedBroadcastListener : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val notificationManager = context.getSystemService(NotificationManager::class.java)
val isGranted = notificationManager.isNotificationPolicyAccessGranted
Log.i("TAG", isGranted.toString())
}
}

Then we can register the broadcast receiver within our context:

import android.app.NotificationManager
import android.content.Context
import android.content.IntentFilter
import android.os.Build
import androidx.core.content.ContextCompat

// Initialize broadcast receiver within your context.
val broadcastReceiver = NotificationPolicyAccessGrantedChangedBroadcastListener()

// Register broadcast receiver to [context].
ContextCompat.registerReceiver(
context,
broadcastReceiver,
IntentFilter(NotificationManager.ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED),
ContextCompat.RECEIVER_NOT_EXPORTED,
)

AutomaticZenRule​

AutomaticZenRule is a class that contains information about Do Not Disturb rule. These rules can be accessed in Settings > Apps & notifications > Notifications > Do Not Disturb > Schedules.

Each item in the image above represent an AutomaticZenRule that dictates when the device goes to Do Not Disturb mode.

Our application can add its own AutomaticZenRule if the user has granted notification policy access as specified in the previous section.

Adding AutomaticZenRule​

The snippet code below shows how to add a simple AutomaticZenRule to your application by using addAutomaticZenRule():

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

However, notice that the AutomaticZenRule that was added will not be activated immediately (its state will have the value STATE_FALSE). Read the next subsections to retrieve and change the state.

Updating AutomaticZenRule​

We can also update our application's previously created AutomaticZenRule by using updateAutomaticZenRule() method:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.service.notification.ZenDeviceEffects

val notificationManager = context.getSystemService(NotificationManager::class.java)
// val automaticZenRuleId = ...
val isSuccess = notificationManager.updateAutomaticZenRule(
automaticZenRuleId,
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
.setDeviceEffects(
ZenDeviceEffects.Builder()
.setShouldUseNightMode(true)
.build()
)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

In the code snippet above, we are updating the rule by adding a setShouldUseNightMode device effect.

Before Android 15 (API Level 35), updating a rule that is not backed up by a ConditionProviderService will deactive the rule (if it was active). Starting from Android 15, the rule will only deactivate if the rule's definition is changing.

Removing AutomaticZenRule​

We can remove our application's AutomaticZenRule by using removeAutomaticZenRule() method:

import android.app.NotificationManager
import android.content.Context

val notificationManager = context.getSystemService(NotificationManager::class.java)
// val automaticZenRuleId = ...
val isSuccess = notificationManager.removeAutomaticZenRule(
automaticZenRuleId,
)

AutomaticZenRule State​

Getting AutomaticZenRule State​

To find out whether our AutomaticZenRule is currently active or not, we can use getAutomaticZenRuleState() method:

import android.app.NotificationManager
import android.content.Context

val notificationManager = context.getSystemService(NotificationManager::class.java)
// val automaticZenRuleId: String = ...
val state = notificationManager.getAutomaticZenRuleState(automaticZenRuleId)

The state could be one of these values:

State valueDescription
STATE_FALSEIndicates that Do Not Disturb should be turned off. Note that all Conditions from all AutomaticZenRule providers must be off for Do Not Disturb to be turned off on the device.
STATE_TRUEIndicates that Do Not Disturb should be turned on.
STATE_UNKNOWNUnknown state.
STATE_ERRORError state.

Changing AutomaticZenRule State​

To change our application AutomaticZenRule's state, we need to use setAutomaticZenRuleState() method:

import android.app.NotificationManager
import android.content.Context
import android.net.Uri
import android.os.Build
import android.service.notification.Condition

val notificationManager = context.getSystemService(NotificationManager::class.java)
// val automaticZenRuleId: String = ...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationManager.setAutomaticZenRuleState(
automaticZenRuleId,
Condition(
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
"Focus Time allows user to do their task without interruption",
Condition.STATE_TRUE,
Condition.SOURCE_USER_ACTION,
)
)
}

In the snippet code above, we're activating the AutomaticZenRule by changing its state to STATE_TRUE.

Specifying AutomaticZenRule State Change Source​

When changing AutomaticZenRule state, we can specify the reason/source of the change by using one of these values:

Source
SOURCE_UNKNOWNThe state is changing due to an unknown reason.
SOURCE_USER_ACTIONThe state is changing due to an explicit user action.
SOURCE_SCHEDULEThe state is changing due to an automatic schedule (alarm, set time, etc).
SOURCE_CONTEXTThe state is changing due to a change in context (such as detected driving or sleeping).

Listening to AutomaticZenRule State Changes​

We can listen to a broadcast intent whenever our application's AutomaticZenRule state changes. To accomplish this, we need to create a broadcast receiver that listens to ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED intent action:

AutomaticZenRuleStateChangedBroadcastReceiver.kt
package com.hanmajid.androidnotebook

import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log

/**
* Simple broadcast receiver that listens to
* [NotificationManager.ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED] intent action.
*/
class AutomaticZenRuleStateChangedBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val automaticZenRuleId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
intent.getStringExtra(NotificationManager.EXTRA_AUTOMATIC_ZEN_RULE_ID)
} else {
null
}
val automaticZenRuleStatus = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
intent.getIntExtra(
NotificationManager.EXTRA_AUTOMATIC_ZEN_RULE_STATUS,
NotificationManager.AUTOMATIC_RULE_STATUS_UNKNOWN,
)
} else {
null
}
Log.i("TAG", "automaticZenRuleId: $automaticZenRuleId")
Log.i("TAG", "automaticZenRuleStatus: $automaticZenRuleStatus")
}
}

Then we can register the broadcast receiver within our context:

import android.app.NotificationManager
import android.content.Context
import android.content.IntentFilter
import android.os.Build
import androidx.core.content.ContextCompat

// Initialize broadcast receiver within your context.
val broadcastReceiver = AutomaticZenRuleStateChangedBroadcastReceiver()

// Register broadcast receiver to [context].
ContextCompat.registerReceiver(
context,
broadcastReceiver,
IntentFilter(NotificationManager.ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED),
ContextCompat.RECEIVER_NOT_EXPORTED,
)

There are several possible state values that we would receive from the broadcast receiver:

StateAPI LevelDescription
AUTOMATIC_RULE_STATUS_UNKNOWN30The current status of the rule is unknown at your target sdk version, and you should continue to provide state changes via setAutomaticZenRuleState().
AUTOMATIC_RULE_STATUS_ENABLED30The given rule currently exists and is enabled. You should continue to provide state changes via setAutomaticZenRuleState().
AUTOMATIC_RULE_STATUS_DISABLED30The given rule currently exists but is disabled. You do not need to continue to provide state changes via setAutomaticZenRuleState() until the rule is reenabled.
AUTOMATIC_RULE_STATUS_REMOVED30The given rule has been deleted.
AUTOMATIC_RULE_STATUS_ACTIVATED35The given rule has been activated by the user or cross device sync.
AUTOMATIC_RULE_STATUS_DEACTIVATED35The given rule has been deactivated ("snoozed") by the user.

AutomaticZenRule Properties​

AutomaticZenRule Interruption Filter​

We can specify the interruption filter that will be applied when the AutomaticZenRule is active by using setInterruptionFilter() method. There are several interruption filters that are available:

INTERRUPTION_FILTER_UNKNOWNReturned when the value is unavailable for any reason.
INTERRUPTION_FILTER_ALLNormal interruption filter - no notifications are suppressed.
INTERRUPTION_FILTER_PRIORITYPriority interruption filter - all notifications are suppressed except those that match the priority criteria. Some audio streams are muted. See Policy#priorityCallSenders, Policy#priorityCategories, Policy#priorityMessageSenders to define or query this criteria. Users can additionally specify packages that can bypass this interruption filter.
INTERRUPTION_FILTER_NONENo interruptions filter - all notifications are suppressed and all audio streams (except those used for phone calls) and vibrations are muted.
INTERRUPTION_FILTER_ALARMSAlarms only interruption filter - all notifications except those of category CATEGORY_ALARM are suppressed. Some audio streams are muted.

AutomaticZenRule Device Effects​

We can specify certain device effects that will be applied when the AutomaticZenRule is active by using setDeviceEffects() method:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.service.notification.ZenDeviceEffects

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
.setDeviceEffects(
ZenDeviceEffects.Builder()
.setShouldDisplayGrayscale(true)
.build()
)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

Currently, there are several device effects that can be applied for your application:

Device EffectDescription
setShouldDimWallpaperSets whether the wallpaper should be dimmed while the rule is active.
setShouldDisplayGrayscaleSets whether the level of color saturation of the display should be set to minimum, effectively switching it to grayscale, while the rule is active.
setShouldSuppressAmbientDisplaySets whether the ambient (always-on) display feature should be disabled while the rule is active. This will have no effect if the device doesn't support always-on display or if it's not generally enabled.
setShouldUseNightModeSets whether night mode (aka dark theme) should be applied while the rule is active.

AutomaticZenRule Type​

It is also possible to set the type of AutomaticZenRule by using setType() method:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
.setType(AutomaticZenRule.TYPE_IMMERSIVE)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

The system will apply special treatments based on the selected type. Currently, these are the available types:

TypeDescription
TYPE_OTHERRule is of a known type, but not one of the specific types.
TYPE_SCHEDULE_TIMEThe type for rules triggered according to a time-based schedule.
TYPE_SCHEDULE_CALENDARThe type for rules triggered by calendar events.
TYPE_BEDTIMEThe type for rules triggered by bedtime/sleeping, like time of day, or snore detection. Only the 'Wellbeing' app may own rules of this type.
TYPE_DRIVINGThe type for rules triggered by driving detection, like Bluetooth connections or vehicle sounds.
TYPE_IMMERSIVEThe type for rules triggered by the user entering an immersive activity, like opening an app using WindowInsetsController#hide(int).
TYPE_THEATERThe type for rules that have a ZenPolicy that implies that the device should not make sound and potentially hide some visual effects; may be triggered when entering a location where silence is requested, like a theater.
TYPE_MANAGEDThe type for rules created and managed by a device owner. These rules may not be fully editable by the device user. Only a 'Device Owner' app may own rules of this type.
TYPE_UNKNOWNRule is of an unknown type. This is the default value if not provided by the owning app, and the value returned if the true type was added in an API level lower than the calling app's targetSdk.

ZenPolicy​

ZenPolicy is an Android class that determines whether AutomaticZenRule allows certain notifications and their corresponding sounds and/or visual effects to play when it's active.

Note that for using ZenPolicy, we have to set the interruption filter to INTERRUPTION_FILTER_PRIORITY.

Allowing/Disallowing Notification Category​

By using ZenPolicy we can allow/disallow certain notification categories. There are several notification categories that can be configured:

Notification CategoryMethodNote
CATEGORY_ALARMallowAlarms(boolean allow)
CATEGORY_EVENTallowEvents(boolean allow)
CATEGORY_REMINDERallowReminders(boolean allow)
CATEGORY_CALLallowCalls(int audienceType)
allowRepeatCallers(boolean allow)For repeated callers.
CATEGORY_MESSAGEallowMessages(int audienceType)

Notice that both allowCalls() and allowMessages() methods require developers to specify the audience type that they want to allow bypass the AutomaticZenRule. There are several audience type that we can use for this:

Audience TypeDescription
PEOPLE_TYPE_UNSETUsed to indicate no preference for the type of people that can bypass dnd for either calls or messages.
PEOPLE_TYPE_ANYONEUsed to indicate all calls or messages can bypass dnd.
PEOPLE_TYPE_CONTACTSUsed to indicate calls or messages from contacts can bypass dnd.
PEOPLE_TYPE_STARREDUsed to indicate calls or messages from starred contacts can bypass dnd.
PEOPLE_TYPE_NONEUsed to indicate no calls or messages can bypass dnd.

Here's an example to how we can use these methods to allow/disallow certain notification categories:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.service.notification.ZenPolicy

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
// Need to set interruption filter to `INTERRUPTION_FILTER_PRIORITY`.
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)
.setZenPolicy(
ZenPolicy.Builder()
.allowAlarms(false)
.allowCalls(ZenPolicy.PEOPLE_TYPE_CONTACTS)
.build()
)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

In the code snippet above, we disallows all alarm notifications and allows notification calls from people from user's contacts.

Allowing Conversation Notification​

We can also allow certain conversation notifications to play sounds and visuall effects by using allowConversations() method.

We can select one of these audience types for the method:

CONVERSATION_SENDERS_UNSETUsed to indicate no preference for the type of conversations that can bypass dnd.
CONVERSATION_SENDERS_ANYONEUsed to indicate all conversations can bypass dnd.
CONVERSATION_SENDERS_IMPORTANTUsed to indicate important conversations can bypass dnd.
CONVERSATION_SENDERS_NONEUsed to indicate no conversations can bypass dnd.

In the code snippet below, we allow only important conversation notifications to bypass the AutomaticZenRule:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.service.notification.ZenPolicy

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)
.setZenPolicy(
ZenPolicy.Builder()
.allowConversations(ZenPolicy.CONVERSATION_SENDERS_IMPORTANT)
.build()
)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

Allowing/Disallowing Notification Sounds & Visual Effects​

It is also possible to allow/disallow notifications from playing their corresponding sound and/or other visual effects by using these methods:

MethodDescription
allowAllSounds()Allows all notifications to bypass DND and unmutes all streams.
disallowAllSounds()Intercepts all notifications and prevents them from playing sounds when DND is active.
showAllVisualEffects()Allows notifications intercepted by DND to show on all surfaces when DND is active.
hideAllVisualEffects()Disallows notifications intercepted by DND from showing when DND is active.
showBadges(boolean show)Whether badges from notifications intercepted by DND are allowed on devices that support badging.
showFullScreenIntent(boolean show)Whether full screen intents that are intercepted by DND are shown.
showInAmbientDisplay(boolean show)Whether notification intercepted by DND are prevented from appearing on ambient displays on devices that support ambient display.
showInNotificationList(boolean show)Whether notification intercepted by DND are prevented from appearing in notification list views like the notification shade or lockscreen on devices that support those views.
showLights(boolean show)Whether notification lights from notifications intercepted by DND are blocked.
showPeeking(boolean show)Whether notifications intercepted by DND are prevented from peeking.
showStatusBarIcons(boolean show)Whether notifications intercepted by DND are prevented from appearing in the status bar on devices that support status bars.
allowSystem(boolean allow)Whether to allow system sounds to play when DND is active.
allowPriorityChannels(boolean allow)Set whether priority channels are permitted to break through DND.

Here's an example of an AutomaticZenRule that disallows sounds:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.service.notification.ZenPolicy

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)
.setZenPolicy(
ZenPolicy.Builder()
.disallowAllSounds()
.build()
)
.setConfigurationActivity(
ComponentName(
context,
MainActivity::class.java
)
)
.build()
)

AutomaticZenRule Configuration Activity​

AutomaticZenRule configuration activity is an activity that will be launched when user taps one of the rules in the Do Not Disturb > Schedules page:

The purpose of this configuration activity is so that user can configure the AutomaticZenRule to their preferences.

In the previous examples, notice that we're using MainActivity as the argument for setConfigurationActivity() method. However, in real applications you should create a special activity for this.

Here's a simple example of such activity:

FocusTimeConfigurationActivity.kt
package com.hanmajid.androidnotebook

import android.app.NotificationManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import com.hanmajid.androidnotebook.ui.theme.AndroidNotebookTheme

class FocusTimeConfigurationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Retrieve the id of the selected `AutomaticZenRule`.
val automaticZenRuleId = intent.extras?.getString(NotificationManager.EXTRA_AUTOMATIC_RULE_ID)
Log.i("TAG", automaticZenRuleId.toString())
}

setContent {
AndroidNotebookTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column {
Text("FocusTimeConfigurationActivity")
}
}
}
}
}
}

Notice that we can retrieve the AutomaticZenRule's id with EXTRA_AUTOMATIC_RULE_ID extra and then we can manipulate the AutomaticZenRule as we like within the activity.

Next, within your AndroidManifest.xml file, you can add a couple of metadata and an intent filter:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

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

<application>
<activity
android:name=".FocusTimeConfigurationActivity"
android:exported="false">
<intent-filter>
<action android:name="android.app.action.AUTOMATIC_ZEN_RULE" />
</intent-filter>
<meta-data
android:name="android.app.zen.automatic.ruleType"
android:value="@string/focus_time_rule_type" />
<meta-data
android:name="android.app.zen.automatic.ruleInstanceLimit"
android:value="1" />
</activity>
</application>

</manifest>
  • The android.app.zen.automatic.ruleType metadata (required) should contain the localized name of the type of the zen rule provided by the activity.
  • The android.app.zen.automatic.ruleInstanceLimit metadata (optional) should contain the maximum number of rule instances that can be created for this rule type. Omit or enter a value <= 0 to allow unlimited instances.

Finally, you can simply pass the activity as an argument when you're building the AutomaticZenRule:

import android.app.AutomaticZenRule
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.net.Uri

val notificationManager = context.getSystemService(NotificationManager::class.java)
val automaticZenRuleId = notificationManager.addAutomaticZenRule(
AutomaticZenRule.Builder(
"Focus Time",
Uri.parse("com.hanmajid.androidnotebook.automaticzenrule.focustime"),
)
.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
.setConfigurationActivity(
ComponentName(
context,
FocusTimeConfigurationActivity::class.java
)
)
.build()
)

References​