
On this article, we will be able to speak about the whole thing about notifications and display you ways you’ll be able to use other notifications with examples.
Subjects to hide:
- Notification Channels
- Soliciting for Notification Permission
- Easy Notification
- Upload Motion in a Notification
- Upload direct answer motion within the Notification
- Upload Growth Bar in Notification
- Beginning an task from a Notification
- Expanded Notification
- Time-sensitive Notification
- Notification Teams
- Notification Badge
- Customized Notification
- Bubbles
A notification is a message that android supplies out of doors your app’s UI to supply details about reminders, signals, verbal exchange from folks, or different well timed data out of your app.
Ahead of beginning, create a brand new Android Undertaking.
You’ll be able to take a look at the code right here.
This can be a illustration of settings that applies to a bunch of notifications. You’ll be able to believe it like other classes of notifications which you’ll be able to configure one after the other. You’ll be able to give other classes of notifications with other habits.
Ranging from Android 8.0(Oreo) you wish to have to assign notifications with a notification channel.
Notice: for those who don’t supply a channel. you are going to no longer get notification from android 8 and above. so please remember to supply a channel.
Let’s see how we create a notification channel:
- Create an object of NotificationChannel and provides it a novel identity, a reputation, and an significance degree. You’ll be able to move an outline textual content that might be proven within the device settings for that notification channel.
remember to guard it with model test as it is just acceptable from Android 8 onwards.
2. Now sign up this channel the use of NotificationManger.
3. Now name this system in onCreate() as you will have to sign up Notification Channels ahead of appearing notifications to customers.
Now, run the app and test the settings of the app.
now, you notice a notification channel has been created. For those who click on at the channel you are going to to find other settings of that channel which I discussed previous.
So, the person can permit/disable sound, vibrations, and so on.
Ranging from Android 13 and above. you wish to have to invite runtime permission to turn a notification. You wish to have to invite for POST_NOTIFICATIONS permission.
<uses-permission android:title="android.permission.POST_NOTIFICATIONS"/>
upload this permission to your Manifest.xml record.
Now, ask this permission to permit.
I’m the use of the accompanist library for simple dealing with of permission supplied by way of google.
implementation "com.google.accompanist:accompanist-permissions:0.27.1"
Now, ask for permission
You, have to test for the Android model as you will have to display this for Android 13 and above. for under API 33, it’s all the time granted.
Now, click on at the button
Settle for it in a different way you’ll be able to ship notifications to the person.
There are a couple of exemptions the place you don’t wish to ask this permission;
- Whether it is associated with Media Periods.
- In case your app is configured to self-manage telephone calls
First, I will be able to display you the anatomy of a notification.
- Small icon: That is required and set with
setSmallIcon()
. - App title: That is supplied by way of the device.
- Timestamp: That is supplied by way of the device however you’ll be able to override it with
setWhen()
or cover it withsetShowWhen(false)
. - Massive icon: That is non-compulsory (in most cases used just for touch footage; don’t use it to your app icon) and set with
setLargeIcon()
. - Identify: That is non-compulsory and set with
setContentTitle()
. - Textual content: That is non-compulsory and set with
setContentText()
.
Let’s create a easy notification
Step 1: Be sure that you’ll be able to import NotificationCompat. if no longer please upload this dependency.
def core_version = "1.6.0"
dependencies {
implementation "androidx.core:core:$core_version"
}
Step 2: Now not you wish to have to create NotificationCompat Builder which is helping us to create a notification by way of including other fields which might be required.
Notice: NotificationCompat is used for gaining access to notification options with backward compatibility. in order that you don’t wish to upload model tests.
You wish to have to have the channel identity with you. in order that notifications can fall into that specific channel which is needed from Android 8 and above. you wish to have to set the concern of notifications for Android 7 and under.
Step 3: Now, you wish to have handy over this notification to the Android device as appearing a notification isn’t a part of your app. You’ll want to move a novel notification identity for that notification.
with(NotificationManagerCompat.from(context)) {
notify(notificationId, builder.construct())
}
You might be finished
You are going to see a notification like this.
Updating a Notification:
To replace this notification after you’ve issued it, name NotificationManagerCompat.notify()
once more, passing it a notification with the similar ID you used prior to now. If the former notification has been pushed aside, a brand new notification is created as an alternative.
Take away a notification:
You’ll be able to upload setAutoCancel to true or use NotificationManagerCompat and speak to cancel() with notification identity
Set lock display visibility:
To keep watch over the extent of element visual within the notification from the lock display.
you wish to have to name setVisibility() and for Android 8 and above
notificationChannel.lockscreenVisibility = Notification.VISIBILITY_SECRET
There are sorts of VISIBILITY
VISIBILITY_PUBLIC
that display the notification’s complete content material.VISIBILITY_SECRET
does not display any a part of this notification at the lock display.VISIBILITY_PRIVATE
displays fundamental data, such because the notification’s icon and the content material name, however hides the notification’s complete content material.
You’ll be able to upload as much as 3 movements in a notification.
Let’s see how we will upload an motion
Step 1: You wish to have a PendingIntent that may include an Intent it may be an task, broadcast receiver, and so on.
I’ve created a BroadCastReceiver and registered it in Manifest.xml
<receiver android:title=".broadcast_receiver.MyBroadCastReceiver"/>
Step 2: Create MyBroadCastReceiver.kt
Step 3: name addAction() on NotificationCompat Builder
builder.addAction(R.drawable.ic_launcher_background ,"Click on",addAction(context,"Click on Motion"))
Now, test the output
When You click on it you are going to get a log with the motion string won.
You’ll have observed direct replies in Chat Apps the place you’ll be able to upload any respond to a dialog. we will be able to be developing that direct answer motion.
Step 1: You wish to have to create a RemoteInput. it’s used to take reaction from a person as this enter isn’t a part of your app which is why it’s Far flung like RemoteViews.
You wish to have to move a String Key which we will be able to use later to get the reaction.
Step 2: Now we will be able to create a PendingIntent as we did above.
Step 3: Now create Motion Builder which is able to assist us to create a relation between the RemoteInput and PendingIntent.
NotificationCompat.Motion.Builder(
androidx.core.R.drawable.notification_action_background,
"Answer", replyPendingIntent)
.addRemoteInput(createRemoteInput())
.construct()
Step 4: Upload motion to the notification
.addAction(replyAction(context))
Let’s see the output
You’ll be able to see the RemoteInput.
now, whilst you click on ship icon. it’ll stay loading as we need to reply to this reaction.
Step 5: Now, we will be able to care for fetching answer textual content and replace notification.
to get the answer you wish to have to move the printed receiver’s intent and fetch the textual content.
right here we’re fetching the message and updating the similar notification the use of identity.
Now, when you click on ship icon. it’ll replace the notification.
6. Upload Growth Bar in Notification :
Now, We will be able to paintings on appearing development in Notification. You’ll have observed this to your telephone.
Step 1: Create a NotificationBuilder
Step 2: In builder, you wish to have to setProgress() with the utmost and present development of the duty for those who don’t know the development of the duty you’ll be able to use an indeterminate development bar.
so, to replace development. you wish to have to run a background assignment and replace the development.
for those who name the process. you are going to see this output.
If you wish to display an indeterminate development bar simply name
setProgress(0,0,true)
So, right here we will be able to see how we will get started an task with a correct navigation revel in for the person. To maintain this navigation revel in, you will have to get started the task with a contemporary assignment. It additionally depends upon the task you display at the faucet of notification.
Common task:
That is an task that exists as part of your app’s standard UX float. So when the person arrives within the task from the notification, the brand new assignment will have to come with an entire again stack, letting them press Again and navigate up the app hierarchy.
Particular task:
The person simplest sees this task if it’s began from a notification. In a way, this task extends the notification UI by way of offering data that will be exhausting to show within the notification itself. So this task does no longer want a again stack. It’s specifically created for Notification.
First, we check out common task pending intent.
TaskStackBuilder:
it supplies a approach to obey the proper conventions round cross-task navigation.
To start out a “common task” out of your notification, arrange the PendingIntent
the use of TaskStackBuilder
in order that it creates a brand new again stack as follows.
Step 1: Outline the herbal hierarchy to your actions by way of including the android:parentActivityName
characteristic to each and every <task>
component to your app manifest record.
Step 2: To start out an task that features a again stack of actions, you wish to have to create an example of TaskStackBuilder
and speak to addNextIntentWithParentStack()
, passing it the Intent
for the task, you wish to have to begin.
Step 3: Create notification builder and setContentIntent with resultIntent.
Right here, Whilst you faucet at the notification. you’ll be able to see no new assignment has been created however now for Particular actions you are going to see a brand new assignment will there.
Let’s get started opening a different task
Step 1: Cross to Manifest.xml and upload this in MainActivity2.
android:taskAffinity=""
android:excludeFromRecents="true"
assignment affinity blended with ACTIVITY_NEW_TASK will assist to not open task in an present assignment.
excludeFromRecents: this may occasionally mean you can to not to find this fresh UI after navigating again.
Step 2: Now, create a PendingIntent with intent having flag ACTIVITY_NEW_TASK.
val notifyIntent = Intent(context, MainActivity2::elegance.java).practice {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val notifyPendingIntent = PendingIntent.getActivity(
context, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
Step 3: notify
So, now you’ll be able to see the brand new assignment and when you press again you are going to no longer see the brand new assignment in fresh.
For those who suppose your app notification will have to display additional info than Easy Notification. Then we will use Expanded Notification. It isn’t a brand new form of notification we will be able to simply upload taste and a couple of extra settings to the notification.
Now, so as to add a big symbol in a notification apply this
Right here, I’m the use of a couple of photographs. you’ll be able to use yours.
You simply have so as to add a mode title BigPictureStyle() and upload your bitmap.
you are going to see one thing like this
you’ll be able to upload this icon as a thumbnail like this
val notification = NotificationCompat.Builder(context, NotificationChannels.CHANNEL1)
.setSmallIcon(R.drawable.table)
.setContentTitle("imageTitle")
.setContentText("imageDescription")
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(icon).bigLargeIcon(null))
.setLargeIcon(icon)
.construct()
bigLargIcon is null as a result of we don’t need to see this thumbnail in expanded shape.
You’ll be able to upload Massive Textual content as neatly
Subsequent up is, appearing dialog textual content.
Easy, use MessageStyle and speak to addMessage() with the message object.
One final is including media controls as we see in song participant apps.
we wish to upload this dependency
implementation "androidx.media:media:1.6.0"
So, right here as you’ll be able to see we’ve added 3 movements within the expanded and collapsed sorts of notification.
Merely, upload movements as we do in notifications but if including movements within the collapsed shape you utilize MediaStyle().
For collapsed shape, you name setActionsInCompatView() and setMediaSessionToken.
When you wish to have to get the person’s consideration for some pressing message. you will have to display time-sensitive notifications.
Step 1: For Android 8 and above you wish to have to set notification channel precedence as HIGH and under set notification of precedence.
val notificationChannel = NotificationChannel(
CHANNEL1,
"channel1",
NotificationManager.IMPORTANCE_HIGH
)
Step 2: The whole thing is identical with the exception of for something
simply setFullScreenIntent as an alternative of setContentIntent.
However if you wish to open full-screen intent. use this code for API 27 and above.
and for Api 26 and under
val flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_FULLSCREEN
window.addFlags(flags)
You are going to see a heads-up notification.
For those who lock the display. you are going to see your task opens
You can have observed this to your telephone.
Grouping notifications is quite common in new android telephones.
In case your app sends notifications. you’ll be able to crew them and upload a abstract notification to them.
you’ll be able to do that as follows:
Step 1: Create a Notification as all the time by way of including setGroup().setGroup will assist to affiliate identical notifications in a bunch that you wish to have to be grouped.
val newMessageNotification1 = NotificationCompat.Builder(context, NotificationChannels.CHANNEL1)
.setSmallIcon(R.drawable.e-mail)
.setContentTitle("Arun")
.setContentText("Ooo")
.setLargeIcon(icon)
.setGroup(GROUP_KEY_WORK_EMAIL)
.construct()
Step 2: you wish to have to create a abstract notification that may assist the person to get an concept concerning the kid notifications.
simply upload the similar crew string and setGroupSummary to true.
You wish to have so as to add InboxStyle to make stronger API 24 and under.
See, it is a abstract notification. for those who make bigger it you are going to see this.
From Android 8 and above android telephone now helps notifications badges.
Those dots seem by way of default in launcher apps that make stronger them and there’s not anything your app must do. Then again, there may well be scenarios wherein you don’t need the notification dot to look or you wish to have to keep watch over precisely which notifications seem there.
recently, you notice a badge.
Disabling a notification badge.
notificationChannel.setShowBadge(false)
Alter Notification Depend:
you’ll be able to trade the message rely by way of:
notification.setNumber(messageCount)
You’ll be able to create your customized format notifications however it isn’t really helpful as your app notification will range from different notifications.
However nonetheless to turn apply this:
Step 1: create your notification format
Step 2: Create an example of faraway view as appearing your notification format isn’t your app process.
use DecoratedCustomViewStyle() and setCustomContentView() together with your faraway view.
In spite of everything, we’ve come to the final section.
This can be a new function in Android 11.
The use of this selection you’ll be able to keep in touch with other people in a floating window.
Let’s see how we will increase this:
Step 1: First, you wish to have to create an example of Individual.
val individual = androidx.core.app.Individual.Builder()
.setName(simpleMessage.sender)
.setIcon(icon)
.setImportant(true)
.construct()
Step 2: Now, create an example of BubbleMetadata.
BubbleMetadata is used to encapsulate the tips had to show a notification as a bubble.
you’ll be able to configure quite a lot of homes for when the bubble is expanded.
right here as you’ll be able to see we want the pendingIntent and icon they are able to’t be null for BubbleMetadata.you’ll be able to set the peak of the floating window.
Step 3: Create an example of ShotcutInfoCompat.
ShotcutInfoCompat: this is helping you get entry to the options of ShortcutInfo.
A shortcut is mainly an motion that your app can carry out and those shortcuts will also be to be had within the telephone launcher.
Step 4: Now you wish to have to put up this shortcut by means of ShortcutManager.
Step 5: Now, create a notification builder and move bubbleMetadata and shortcut identity. you wish to have to care for backward compatibility as neatly
Step 6: name the process by way of passing information.
BubbleNotificationView(context).showNotification(
Message(
123,
"Arun",
"Hi",
R.drawable.ic_base_person
)
)
Step 7: You’ll want to upload those homes resizeable and embedded. On units working Android 10, notifications aren’t proven as bubbles except you explicitly set documentLaunchMode
to "all the time"
Now, for those who run the app.
Now, we’ve come to the tip of the object.
You’ll be able to take a look at the code right here.
Thank You for studying.