Android - Showing notifications

by 19:02 0 comments
In this tutorial, we will use Android Studio to show notifications

We start by creating a new Android studio project
Choose the app name as NotificationApp, package name as com.tutorial.notification.ammar

Then you can copy and paste this xml to your layout

This code is a simple linear layout with two buttons, one for showing toast and the other for showing notification in the notification bar.

Now let's look at the java code
This code is simple too.
We are identifying the buttons with their id, then we are adding onClickListner to them.
The toast button just is easy, you are using Toast class, calling makeText method, passing to it the context, the string you want to show and the time of it to stay, there is two options for the time Toast.LENGTH_SHORT for short period and Toast.LENGTH_LONG for long periods

The other buttons makes a notification with a notification builder, Notification Builder takes a context, then you call setSmallIcon, setTitleText and setContentText to form the shape of the notification.
Last thing to do is adding intent to it, this must be pending intent, so you can just make an intent to pass it to a pending intent which you have to pass to the method setContentIntent.
The notification Builder is ready so we are making a reference to the notification manager then calling it to notify with our notification after it is built.

Good luck with coding.

Ammar Atef

Blog Creator

Always work and you will be happy, Writing code, designing system and learning some thing new, I call that real life, No matter what is the problem, humanity can solve it any way, Creative one who believes he is creative, Who really watch, think, try and success, World is watching us because we are engineers.


Post a Comment