How to Make My Andriod Send Me Calendar Alerts Again

Notifications provide short, timely information about events in your app while it's not in use. This page teaches you how to create a notification with diverse features for Android 4.0 (API level 14) and higher. For an introduction to how notifications announced on Android, see the Notifications Overview. For sample code that uses notifications, see the Android Notifications Sample.

Notice that the code on this folio uses the NotificationCompat APIs from the Android support library. These APIs permit y'all to add together features available only on newer versions of Android while all the same providing compatibility dorsum to Android 4.0 (API level 14). However, some new features such as the inline reply action result in a no-op on older versions.

Add the support library

Although most projects created with Android Studio include the necessary dependencies to use NotificationCompat, yous should verify that your module-level build.gradle file includes the post-obit dependency:

Groovy

val core_version = "1.6.0" dependencies {     implementation "androidx.core:cadre:$core_version" }            

Kotlin

val core_version = "1.6.0" dependencies {     implementation("androidx.core:core-ktx:$core_version") }            

Create a basic notification

A notification in its most basic and compact form (also known every bit collapsed class) displays an icon, a title, and a small amount of content text. In this section, you'll learn how to create a notification that the user can click on to launch an action in your app.

Effigy 1. A notification with a championship and text

For more details virtually each office of a notification, read about the notification anatomy.

Set the notification content

To go started, you need to set the notification'southward content and aqueduct using a NotificationCompat.Builder object. The following example shows how to create a notification with the post-obit:

  • A small icon, set by setSmallIcon(). This is the merely user-visible content that's required.
  • A title, prepare by setContentTitle().
  • The body text, set by setContentText().
  • The notification priority, set by setPriority(). The priority determines how intrusive the notification should be on Android vii.1 and lower. (For Android 8.0 and higher, you must instead gear up the aqueduct importance—shown in the next section.)

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle(textTitle)         .setContentText(textContent)         .setPriority(NotificationCompat.PRIORITY_DEFAULT)            

Coffee

NotificationCompat.Architect builder = new NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle(textTitle)         .setContentText(textContent)         .setPriority(NotificationCompat.PRIORITY_DEFAULT);            

Notice that the NotificationCompat.Builder constructor requires that you provide a channel ID. This is required for compatibility with Android viii.0 (API level 26) and higher, but is ignored by older versions.

Past default, the notification'south text content is truncated to fit one line. If you lot want your notification to exist longer, you can enable an expandable notification by adding a fashion template with setStyle(). For case, the following code creates a larger text surface area:

Kotlin

var builder = NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Much longer text that cannot fit 1 line...")              .setStyle(NotificationCompat.BigTextStyle()                 .bigText("Much longer text that cannot fit one line..."))              .setPriority(NotificationCompat.PRIORITY_DEFAULT)            

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Much longer text that cannot fit one line...")              .setStyle(new NotificationCompat.BigTextStyle()                 .bigText("Much longer text that cannot fit one line..."))              .setPriority(NotificationCompat.PRIORITY_DEFAULT);            

For more information near other large notification styles, including how to add an image and media playback controls, encounter Create a Notification with Expandable Detail.

Create a aqueduct and set the importance

Earlier you lot can deliver the notification on Android 8.0 and higher, you must register your app's notification channel with the system by passing an example of NotificationChannel to createNotificationChannel(). So the following lawmaking is blocked by a condition on the SDK_INT version:

Kotlin

individual fun createNotificationChannel() {     // Create the NotificationChannel, just merely on API 26+ because     // the NotificationChannel course is new and not in the support library     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {         val proper name = getString(R.string.channel_name)         val descriptionText = getString(R.string.channel_description)         val importance = NotificationManager.IMPORTANCE_DEFAULT         val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {             description = descriptionText         }         // Register the channel with the organisation         val notificationManager: NotificationManager =             getSystemService(Context.NOTIFICATION_SERVICE) every bit NotificationManager         notificationManager.createNotificationChannel(aqueduct)     } }            

Java

private void createNotificationChannel() {     // Create the NotificationChannel, but just on API 26+ because     // the NotificationChannel class is new and not in the back up library     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {         CharSequence name = getString(R.cord.channel_name);         String description = getString(R.string.channel_description);         int importance = NotificationManager.IMPORTANCE_DEFAULT;         NotificationChannel aqueduct = new NotificationChannel(CHANNEL_ID, proper name, importance);         channel.setDescription(description);         // Register the aqueduct with the system; you can't change the importance         // or other notification behaviors afterwards this         NotificationManager notificationManager = getSystemService(NotificationManager.class);         notificationManager.createNotificationChannel(channel);     } }            

Because you must create the notification channel before posting whatever notifications on Android 8.0 and higher, you should execute this code as before long equally your app starts. It'southward safe to call this repeatedly because creating an existing notification channel performs no operation.

Discover that the NotificationChannel constructor requires an importance, using i of the constants from the NotificationManager grade. This parameter determines how to interrupt the user for any notification that belongs to this channel—though you must also fix the priority with setPriority() to back up Android 7.1 and lower (every bit shown in a higher place).

Although you must set up the notification importance/priority equally shown here, the system does not guarantee the warning behavior y'all'll become. In some cases the system might change the importance level based other factors, and the user can ever redefine what the importance level is for a given channel.

For more than data nearly what the dissimilar levels hateful, read almost notification importance levels.

Set the notification'south tap action

Every notification should respond to a tap, usually to open an activity in your app that corresponds to the notification. To practice and so, you must specify a content intent defined with a PendingIntent object and pass it to setContentIntent().

The following snippet shows how to create a bones intent to open up an activity when the user taps the notification:

Kotlin

// Create an explicit intent for an Activity in your app              val intent = Intent(this, AlertDetails::class.coffee).apply {     flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }              val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)  val builder = NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("How-do-you-do World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)         // Fix the intent that volition fire when the user taps the notification              .setContentIntent(pendingIntent)              .setAutoCancel(truthful)            

Coffee

// Create an explicit intent for an Activity in your app              Intent intent = new Intent(this, AlertDetails.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);              PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);  NotificationCompat.Builder builder = new NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hello World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)         // Gear up the intent that volition fire when the user taps the notification              .setContentIntent(pendingIntent)              .setAutoCancel(true);            

Notice this code calls setAutoCancel(), which automatically removes the notification when the user taps information technology.

The setFlags() method shown above helps preserve the user's expected navigation experience after they open your app via the notification. But whether yous desire to use that depends on what type of activity you're starting, which may be 1 of the following:

  • An activity that exists exclusively for responses to the notification. There's no reason the user would navigate to this activity during normal app use, so the activity starts a new task instead of being added to your app'due south existing task and back stack. This is the type of intent created in the sample above.
  • An activity that exists in your app's regular app flow. In this example, starting the activity should create a back stack so that the user's expectations for the Dorsum and Up buttons is preserved.

For more than almost the dissimilar ways to configure your notification'south intent, read Start an Activity from a Notification.

Show the notification

To make the notification appear, phone call NotificationManagerCompat.notify(), passing information technology a unique ID for the notification and the issue of NotificationCompat.Builder.build(). For instance:

Kotlin

with(NotificationManagerCompat.from(this)) {     // notificationId is a unique int for each notification that you must ascertain     notify(notificationId, architect.build()) }            

Coffee

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);  // notificationId is a unique int for each notification that y'all must ascertain notificationManager.notify(notificationId, builder.build());            

Remember to save the notification ID that you pass to NotificationManagerCompat.notify() considering you'll need it after if you want to update or remove the notification.

Add action buttons

A notification can offer up to three action buttons that allow the user to respond apace, such as snooze a reminder or even answer to a text message. But these action buttons should not indistinguishable the activeness performed when the user taps the notification.

Figure 2. A notification with i action button

To add an activity button, laissez passer a PendingIntent to the addAction() method. This is just like setting upwardly the notification's default tap activity, except instead of launching an activeness, y'all tin can exercise a diversity of other things such as start a BroadcastReceiver that performs a job in the background then the action does non interrupt the app that'due south already open.

For example, the following code shows how to send a broadcast to a specific receiver:

Kotlin

              val snoozeIntent = Intent(this, MyBroadcastReceiver::class.java).apply {     action = ACTION_SNOOZE     putExtra(EXTRA_NOTIFICATION_ID, 0) } val snoozePendingIntent: PendingIntent =     PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)              val builder = NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hello World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)         .setContentIntent(pendingIntent)              .addAction(R.drawable.ic_snooze, getString(R.cord.snooze),                 snoozePendingIntent)            

Java

              Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class); snoozeIntent.setAction(ACTION_SNOOZE); snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0); PendingIntent snoozePendingIntent =         PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);              NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hello Earth!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)         .setContentIntent(pendingIntent)              .addAction(R.drawable.ic_snooze, getString(R.string.snooze),                 snoozePendingIntent);            

For more data about edifice a BroadcastReceiver to run background work, meet the Broadcasts guide.

If yous're instead trying to build a notification with media playback buttons (such equally to intermission and skip tracks), see how to create a notification with media controls.

Add a direct reply action

The straight reply action, introduced in Android vii.0 (API level 24), allows users to enter text directly into the notification, which is delivered to your app without opening an activity. For instance, y'all can apply a direct answer activeness to permit users reply to text messages or update task lists from within the notification.

Effigy three. Tapping the "Reply" push button opens the text input

The direct reply activity appears equally an boosted button in the notification that opens a text input. When the user finishes typing, the system attaches the text response to the intent y'all had specified for the notification action and sends the intent to your app.

Add together the reply push button

To create a notification activeness that supports straight reply:

  1. Create an instance of RemoteInput.Builder that you lot can add to your notification action. This class's constructor accepts a cord that the organisation uses as the key for the text input. Later, your handheld app uses that key to retrieve the text of the input.

    Kotlin

    // Key for the string that's delivered in the action's intent. private val KEY_TEXT_REPLY = "key_text_reply" var replyLabel: String = resources.getString(R.cord.reply_label) var remoteInput: RemoteInput = RemoteInput.Architect(KEY_TEXT_REPLY).run {     setLabel(replyLabel)     build() }                

    Java

    // Fundamental for the string that's delivered in the action'due south intent. private static last String KEY_TEXT_REPLY = "key_text_reply";  Cord replyLabel = getResources().getString(R.cord.reply_label); RemoteInput remoteInput = new RemoteInput.Architect(KEY_TEXT_REPLY)         .setLabel(replyLabel)         .build();                
  2. Create a PendingIntent for the respond activity.

    Kotlin

    // Build a PendingIntent for the reply activeness to trigger. var replyPendingIntent: PendingIntent =     PendingIntent.getBroadcast(applicationContext,         chat.getConversationId(),         getMessageReplyIntent(conversation.getConversationId()),         PendingIntent.FLAG_UPDATE_CURRENT)                

    Java

    // Build a PendingIntent for the answer activity to trigger. PendingIntent replyPendingIntent =         PendingIntent.getBroadcast(getApplicationContext(),                 conversation.getConversationId(),                 getMessageReplyIntent(conversation.getConversationId()),                 PendingIntent.FLAG_UPDATE_CURRENT);                

    Caution: If you re-use a PendingIntent, a user may answer to a different conversation than the one they thought they did. You must either provide a request code that is different for each conversation or provide an intent that doesn't return true when you call equals() on the answer intent of any other conversation. The conversation ID is frequently passed as part of the intent's extras packet, but is ignored when you lot call equals().

  3. Attach the RemoteInput object to an action using addRemoteInput().

    Kotlin

    // Create the answer action and add together the remote input. var activity: NotificationCompat.Activeness =     NotificationCompat.Activeness.Builder(R.drawable.ic_reply_icon,         getString(R.string.label), replyPendingIntent)         .addRemoteInput(remoteInput)         .build()                

    Java

    // Create the reply action and add the remote input. NotificationCompat.Activity action =         new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,                 getString(R.string.label), replyPendingIntent)                 .addRemoteInput(remoteInput)                 .build();                
  4. Apply the activeness to a notification and issue the notification.

    Kotlin

    // Build the notification and add together the action. val newMessageNotification = Notification.Builder(context, CHANNEL_ID)         .setSmallIcon(R.drawable.ic_message)         .setContentTitle(getString(R.string.title))         .setContentText(getString(R.string.content))         .addAction(action)         .build()  // Issue the notification. with(NotificationManagerCompat.from(this)) {     notificationManager.notify(notificationId, newMessageNotification) }                

    Java

    // Build the notification and add the action. Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID)         .setSmallIcon(R.drawable.ic_message)         .setContentTitle(getString(R.string.title))         .setContentText(getString(R.string.content))         .addAction(action)         .build();  // Issue the notification. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, newMessageNotification);                

The system prompts the user to input a response when they trigger the notification action, equally shown in figure iii.

Recall user input from the reply

To receive user input from the notification's reply UI, call RemoteInput.getResultsFromIntent(), passing it the Intent received by your BroadcastReceiver:

Kotlin

private fun getMessageText(intent: Intent): CharSequence? {     render RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_TEXT_REPLY) }            

Java

private CharSequence getMessageText(Intent intent) {     Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);     if (remoteInput != null) {         return remoteInput.getCharSequence(KEY_TEXT_REPLY);     }     return cipher;  }            

After yous've candy the text, you must update the notification by calling NotificationManagerCompat.notify() with the same ID and tag (if used). This is necessary to hibernate directly respond UI and confirm to the user that their reply was received and processed correctly.

Kotlin

// Build a new notification, which informs the user that the arrangement // handled their interaction with the previous notification. val repliedNotification = Notification.Builder(context, CHANNEL_ID)         .setSmallIcon(R.drawable.ic_message)         .setContentText(getString(R.string.replied))         .build()  // Result the new notification. NotificationManagerCompat.from(this).apply {     notificationManager.notify(notificationId, repliedNotification) }            

Java

// Build a new notification, which informs the user that the system // handled their interaction with the previous notification. Notification repliedNotification = new Notification.Builder(context, CHANNEL_ID)         .setSmallIcon(R.drawable.ic_message)         .setContentText(getString(R.string.replied))         .build();  // Issue the new notification. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, repliedNotification);            

When working with this new notification, utilize the context that's passed to the receiver's onReceive() method.

You should as well append the answer to the bottom of the notification by calling setRemoteInputHistory(). However, if you're building a messaging app, you lot should create a messaging-style notification and append the new bulletin to the chat.

For more advice for notifications from a messaging apps, meet best practices for messaging apps.

Add a progress bar

Notifications can include an animated progress indicator that shows users the status of an ongoing operation.

Figure 4. The progress bar during and after the operation.

If you can guess how much of the operation is consummate at whatsoever time, employ the "determinate" class of the indicator (as shown in figure 4) by calling setProgress(max, progress, false). The first parameter is what the "complete" value is (such every bit 100); the second is how much is currently consummate, and the last indicates this is a determinate progress bar.

As your performance proceeds, continuously call setProgress(max, progress, false) with an updated value for progress and re-upshot the notification.

Kotlin

val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {     setContentTitle("Moving picture Download")     setContentText("Download in progress")     setSmallIcon(R.drawable.ic_notification)     setPriority(NotificationCompat.PRIORITY_LOW) } val PROGRESS_MAX = 100 val PROGRESS_CURRENT = 0 NotificationManagerCompat.from(this).apply {     // Issue the initial notification with nil progress     architect.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)     notify(notificationId, architect.build())      // Do the job here that tracks the progress.     // Usually, this should be in a     // worker thread     // To show progress, update PROGRESS_CURRENT and update the notification with:     // architect.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);     // notificationManager.notify(notificationId, builder.build());      // When done, update the notification one more time to remove the progress bar     architect.setContentText("Download complete")             .setProgress(0, 0, false)     notify(notificationId, builder.build()) }            

Java

... NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); NotificationCompat.Architect builder = new NotificationCompat.Architect(this, CHANNEL_ID); builder.setContentTitle("Movie Download")         .setContentText("Download in progress")         .setSmallIcon(R.drawable.ic_notification)         .setPriority(NotificationCompat.PRIORITY_LOW);  // Issue the initial notification with goose egg progress int PROGRESS_MAX = 100; int PROGRESS_CURRENT = 0; builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, fake); notificationManager.notify(notificationId, builder.build());  // Do the job hither that tracks the progress. // Unremarkably, this should be in a // worker thread // To show progress, update PROGRESS_CURRENT and update the notification with: // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false); // notificationManager.notify(notificationId, builder.build());  // When washed, update the notification one more than time to remove the progress bar builder.setContentText("Download consummate")         .setProgress(0,0,false); notificationManager.notify(notificationId, builder.build());            

At the terminate of the operation, progress should equal max. Y'all can either leave the progress bar showing when the operation is done, or remove it. In either case, think to update the notification text to show that the functioning is complete. To remove the progress bar, call setProgress(0, 0, false).

To display an indeterminate progress bar (a bar that does not signal percent complete), telephone call setProgress(0, 0, truthful). The result is an indicator that has the same mode as the progress bar to a higher place, except the progress bar is a continuous animation that does not indicate completion. The progress blitheness runs until yous telephone call setProgress(0, 0, false) and so update the notification to remove the activity indicator.

Call back to change the notification text to indicate that the operation is consummate.

Set up a organisation-wide category

Android uses some pre-defined arrangement-broad categories to determine whether to disturb the user with a given notification when the user has enabled Do Not Disturb style.

If your notification falls into one of the pre-defined notification categories defined in NotificationCompat—such as CATEGORY_ALARM, CATEGORY_REMINDER, CATEGORY_EVENT, or CATEGORY_CALL—you should declare it every bit such by passing the appropriate category to setCategory().

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hi World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)              .setCategory(NotificationCompat.CATEGORY_MESSAGE)            

Coffee

NotificationCompat.Builder builder = new NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hello World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)              .setCategory(NotificationCompat.CATEGORY_MESSAGE);            

This information almost your notification category is used by the system to make decisions almost displaying your notification when the device is in Do Non Disturb mode.

However, you are non required to set a system-wide category and should merely exercise then if your notifications match ane of the categories defined by in NotificationCompat.

Bear witness an urgent bulletin

Your app might demand to brandish an urgent, time-sensitive message, such every bit an incoming phone phone call or a ringing warning. In these situations, you can associate a total-screen intent with your notification. When the notification is invoked, users encounter one of the following, depending on the device'due south lock status:

  • If the user'due south device is locked, a full-screen activity appears, covering the lockscreen.
  • If the user'southward device is unlocked, the notification appears in an expanded course that includes options for handling or dismissing the notification.

The post-obit code snippet demonstrates how to associate your notification with a full-screen intent:

Kotlin

val fullScreenIntent = Intent(this, ImportantActivity::class.java) val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,     fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)  var builder = NotificationCompat.Builder(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hullo World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)              .setFullScreenIntent(fullScreenPendingIntent, true)            

Java

Intent fullScreenIntent = new Intent(this, ImportantActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,         fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);  NotificationCompat.Builder builder = new NotificationCompat.Architect(this, CHANNEL_ID)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("How-do-you-do World!")         .setPriority(NotificationCompat.PRIORITY_DEFAULT)              .setFullScreenIntent(fullScreenPendingIntent, true);            

Set up lock screen visibility

To control the level of particular visible in the notification from the lock screen, call setVisibility() and specify ane of the following values:

  • VISIBILITY_PUBLIC shows the notification's total content.
  • VISIBILITY_SECRET doesn't show whatsoever part of this notification on the lock screen.
  • VISIBILITY_PRIVATE shows bones data, such equally the notification's icon and the content championship, but hides the notification'south full content.

When VISIBILITY_PRIVATE is set up, you can besides provide an alternate version of the notification content which hides certain details. For example, an SMS app might display a notification that shows You have 3 new text letters, simply hides the message contents and senders. To provide this culling notification, get-go create the alternative notification with NotificationCompat.Builder as usual. So adhere the alternative notification to the normal notification with setPublicVersion().

However, the user always has final control over whether their notifications are visible on the lock screen and tin fifty-fifty command that based on your app's notification channels.

Update a notification

To update this notification afterward you've issued it, call NotificationManagerCompat.notify() again, passing it a notification with the same ID you used previously. If the previous notification has been dismissed, a new notification is created instead.

You tin optionally call setOnlyAlertOnce() so your notification interupts the user (with sound, vibration, or visual clues) only the get-go time the notification appears and not for after updates.

Remove a notification

Notifications remain visible until one of the following happens:

  • The user dismisses the notification.
  • The user clicks the notification, and you chosen setAutoCancel() when you created the notification.
  • You lot telephone call cancel() for a specific notification ID. This method as well deletes ongoing notifications.
  • You call cancelAll(), which removes all of the notifications you lot previously issued.
  • If you set a timeout when creating a notification using setTimeoutAfter(), the system cancels the notification subsequently the specified duration elapses. If required, you can cancel a notification before the specified timeout duration elapses.

All-time practices for messaging apps

Utilise the all-time practices listed here every bit a quick reference of what to keep in mind when creating notifications for your messaging and chat apps.

Apply MessagingStyle

Starting in Android seven.0 (API level 24), Android provides a notification mode template specifically for messaging content. Using the NotificationCompat.MessagingStyle class, yous can modify several of the labels displayed on the notification, including the conversation title, boosted messages, and the content view for the notification.

The post-obit code snippet demonstrates how to customize a notification's way using the MessagingStyle class.

Kotlin

var notification = NotificationCompat.Builder(this, CHANNEL_ID)         .setStyle(NotificationCompat.MessagingStyle("Me")                 .setConversationTitle("Team dejeuner")                 .addMessage("How-do-you-do", timestamp1, null) // Pass in null for user.                 .addMessage("What'south upwardly?", timestamp2, "Coworker")                 .addMessage("Non much", timestamp3, null)                 .addMessage("How nearly lunch?", timestamp4, "Coworker"))         .build()            

Java

Notification notification = new Notification.Builder(this, CHANNEL_ID)         .setStyle(new NotificationCompat.MessagingStyle("Me")                 .setConversationTitle("Team dejeuner")                 .addMessage("How-do-you-do", timestamp1, aught) // Laissez passer in null for user.                 .addMessage("What's up?", timestamp2, "Coworker")                 .addMessage("Non much", timestamp3, null)                 .addMessage("How well-nigh lunch?", timestamp4, "Coworker"))         .build();            

Starting in Android viii.0 (API level 26), notifications that use the NotificationCompat.MessagingStyle class display more content in their collapsed course. You can besides use the addHistoricMessage() method to provide context to a conversation by adding historic messages to messaging-related notifications.

When using NotificationCompat.MessagingStyle:

  • Call MessagingStyle.setConversationTitle() to gear up a title for group chats with more than two people. A good conversation title might exist the proper name of the group chat or, if it doesn't have a specific name, a list of the participants in the conversation. Without this, the message may exist mistaken every bit belonging to a one-to-1 conversation with the sender of the most recent message in the conversation.
  • Utilise the MessagingStyle.setData() method to include media messages such every bit images. MIME types, of the pattern image/* are currently supported.

Use direct reply

Straight Reply allows a user to reply inline to a message.

  • After a user replies with the inline reply activeness, use MessagingStyle.addMessage() to update the MessagingStyle notification and practise not retract or cancel the notification. Not cancelling the notification allows a user to send multiple replies from the notification.
  • To make the inline reply action compatible with Vesture Os, call Action.WearableExtender.setHintDisplayInlineAction(true).
  • Use the addHistoricMessage() method to provide context to a direct answer conversation past calculation celebrated messages to the notification.

Enable smart reply

  • To enable Smart Respond, call setAllowGeneratedResponses(true) on the respond action. This causes Smart Reply responses to be available to users when the notification is bridged to a Wear Bone device. Smart Reply responses are generated by an entirely on-watch machine learning model using the context provided past the NotificationCompat.MessagingStyle notification, and no information is uploaded to the Cyberspace to generate the responses.

Add notification metadata

  • Assign notification metadata to tell the organisation how to handle your app notifications when the device is in Practice Not Disturb mode. For case, use the addPerson() or setCategory(Notification.CATEGORY_MESSAGE) method to override the Practice Not Disturb mode.

boozerwrond1963.blogspot.com

Source: https://developer.android.com/training/notify-user/build-notification

0 Response to "How to Make My Andriod Send Me Calendar Alerts Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel