So you’ve built your first Android app and you’re thinking of how can you improve it. The thing that you need is a notification.
Think about it. Every good application has some sort of a notification. For example, YouTube notifies you with a recommendation video or when a YouTuber you are subscribed to uploads a video, Facebook notifies you when someone comments on your picture or when you get a message (actually, the Facebook app requires a stand alone app for messaging, i.e. Messenger, unless you get the Lite… not cool Facebook), and so on.
If you haven’t realised yet, your app needs to have some sort of notification. There are some cases when a notification is not needed. Some times notifications can be extremely annoying (I’m gonna throw Facebook under the bus. I do not need to get a notifications every time a friend of mine comments or likes something)
Today, I am going to teach you how to build a simple notification. We are going to build an app that sends a notification every time you press a button. I am going to provide a link to the full project at the end of the lesson.
Step 1: Make a new Android Project
I am going to name my project Notification.
On the Target Android Devices tab select Phone and Tablets and select API 15 as the minimum required API (around 95% of all Android devices run API 15 or higher).
Choose the Empty Activity. I am going to leave the default name of the activity.
Click Finish and let’s start coding!
Step 2: Build the logic behind the app
First we’ll make a button show up in the screen. To do that open the activity_main.xml file (\app\src\main\res\layout\activity_main.xml). We’ll begin by changing the layout of the activity from Relative Layout to Linear Layout.
To do this, simply replace RelativeLayout to LinearLayout and add the tag android:orientation=”vertical”.
This is how the activity_main.xml file should look now:
Now we’ll be adding a button. Replace the TextView element with the following code:
Now, we’re heading to the MainActivity.java file (\app\src\main\java\com\markojerkic\notification\MainActivity.java)
First you need to find the Button view in the java code. To do so you need to use the findViewById() method. Copy the Following code:
Now we need to set up a onClickListener:
You will need to write a method that build a notification. We’ll do it like this:
This is a very simple example of what you can do with a notification. You can run almost an entire application from it’s notifications (for example, a lot of people see their music playing app almost exclusively through the notification of the app).
We’ll be going through the logic of Android notifications together, and hopefully both of us will learn something throughout this journey.
Full app project on Github: https://github.com/makkam012/simple_notification