Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement Notifications in Android

In this tutorial we are going to learn how to create a notification in status bar.

Notification is a kind of message which displayed normally outside the UI of an application. Notification’s role is to inform user about event that requires attention.

Notifications service running in background will not intrude an activity to inform any event in foreground because activity has highest priority. Notifications can be displayed once or desired number of times. A notification with in status bar appears as an icon as well as some short text.

Here are the below some examples of notifications:

  • Alarm Clocks
  • SMS Indicators
  • Birthday Remainder etc.

Objective:

  • To provide knowledge about the notifications in android.
  • To provide implementation of status bar notification.
  • To provide functionality of PendingIntent class.

Classes used to perform this task:

  • Notification class.
  • NotificationManager class.
  • Intent class.
  • PendingIntent class.

Introduction to classes used:

Notification class: This class represents that how a persistent notification can be present by using NotificationManager. Here is below the commonly used method:

void setLatestEventInfo(Content ctx, CharSequence contitle, CharSequence contentext, PendingIntent penintent): This method is used to create the notification in status bar.

  • ctx - This is the context for the Activity.
  • Contitle - This is the title which goes in the expanded entry.
  • Contetext - This is the text which goes in the expanded entry.
  • Penintent - This is the intent which is responsible to navigate to the specified activity when user click on the notification in expanded view.

NotificationManager class: This class is used to notifiy the user that event happened. This is the way how you tell that somethings has happened in background.

Notifications can be of different forms like:

  • A persistent icon that always goes in status bar and can be accesible through the launcher.
  • Turning ON or flashing the LED’S on device.
  • Alerting the user by playing a sound, flashing the backlight, or vibrating.

Here are below the methods of this class which are commonly used:

  • void cancel(int ID): This method is used to cancel the previously shown notification.
  • void cancelAll(): This method is used to cancel all the previously shown notification.
  • void notify(int Id, Notification notification): This method is used to post a notification to be shown in the status bar.

Intent Class: Intent class is used to navigate the user to another activity which is defined in the Intent. When user will click on the notification from expanded view then intent will fire.

Here are below some methods which are commonly used in this project:

void startActivity(intent): This method is used to start the activity which is specified in Intent.

PendingIntent class: This class acts as a description of intent and the target action that is to perform with it. Here are below some commoly used methods:

  • void cancel(): This method is used to cancel the current active Pending Intent.
  • static PendingIntent getActivity(Context ctx, int reqCode,Intent intent, int Flags): This method is used to reterive a PendingIntent that will start a new activity.

Steps are used to complete this project:

Create a new Android project and name it “NotificationShow” and package name should be “com.jmd.notificationshow”.

 Project name should be NotificationShow

Figure 1: Project name should be NotificationShow

Package name should be com.jmd.notificationshow

Figure 2: Package name should be com.jmd.notificationshow

Listing 1: Paste the following code inside the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="25px"
       
        android:layout_marginTop="50px"
        android:text="Notification" />

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50px"
         android:layout_below="@+id/notification"
        android:text="Start" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/start"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50px"
        android:text="Clear" />

</RelativeLayout>

Listing 2: Paste the following code inside the NotificationShowActivity.java

package com.jmd.notificationshow;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NotificationShowActivity extends Activity implements
		OnClickListener {
	Button start, clear;
	Notification noti;
	NotificationManager nmgr;
	public static final int NOTIFICATION_ID = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		getInit();
		nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		noti = new Notification(R.drawable.ic_launcher,"Today is you meeting", System.currentTimeMillis());
		Intent intent = new Intent(this,Navigation.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
		noti.setLatestEventInfo(this, "Event Header","Today is your meeting", pIntent);
	}

	public void getInit() {
		start = (Button) findViewById(R.id.start);
		clear = (Button) findViewById(R.id.clear);
		start.setOnClickListener(this);
		clear.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId())
		{
		case R.id.start:
			nmgr.notify(NOTIFICATION_ID,noti);
			break;
		case R.id.clear:
			nmgr.cancel(NOTIFICATION_ID);
		}

	}
}

Listing 3: Make another class inside the package com.jmd.notificationshow and name it Navigation then put the following code inside it:

package com.jmd.notificationshow;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Navigation extends Activity {
	TextView text;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		text = new TextView(this);
		text.setText("Welcome to new Activity");
		setContentView(text);
	}
}

Listing 4: Put the following entry inside the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jmd.notificationshow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".NotificationShowActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
         <activity
            android:name=".Navigation"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>

Run your project and here is the output will come:

Starting screen of activity

Figure 3: Starting screen of activity

Notification will appear at top when user click on start button

Figure 4: Notification will appear at top when user click on start button

Notification shown in expand view.

Figure 5: Notification shown in expand view.

Activity screen after click on start button.

Figure 6: Activity screen after click on start button.

Explanation of above code:

The getInit() method: This method is used to initialize the view within activity and for the registration of buttons.

public void getInit() {
		start = (Button) findViewById(R.id.start);
		clear = (Button) findViewById(R.id.clear);
		start.setOnClickListener(this);
		clear.setOnClickListener(this);
	}

This line of code will get the System Service for notificaton for notification manager

nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

This line of code will show the notification in status bar

noti = new Notification(R.drawable.ic_launcher,"Today is you meeting", System.currentTimeMillis());

This line of code is used to set the notificaition in notification panel.

noti.setLatestEventInfo(this, "Event Header","Today is your meeting", pIntent);

The onClick(View v) method: It has 2 cases one is for start button and other one is for clear button. When user will click on start button then notification will appear and when user will click on clear button then notificatonnotification will be cleared.

public void onClick(View v) {
		switch(v.getId())
		{
		case R.id.start:
			nmgr.notify(NOTIFICATION_ID,noti);
			break;
		case R.id.clear:
			nmgr.cancel(NOTIFICATION_ID);
		}

	}
}

What is Covered ?

  • Implementation of Notifications.
  • Familiarity with NotificationManager, Notification, Intent, PendingIntent classes and their methods.
  • How to start and clear notifications.


Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login