Monday, 2 December 2013

Simple Notification in android

Notification:

                          Notifications are a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information. 


Notification on Android can be done in any of the following ways:
  • Status Bar Notification
  • Vibrate
  • Flash lights
  • Play a sound
Through the Notification, we can allow the user to launch a new activity as well.

To create a status bar notification, we'll need to use two classes: Notification and NotificationManager.
  • Notification
    Defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.
  • NotificationManager
    NotificationManager is an android system service that executes and manages all notifications. Hence we cannot create an instance of the NotificationManager but we can retrieve a reference to it by calling the getSystemService() method.
Once we got this handle, we invoke the notify() method on it by passing the notification object created.

So far, we have all the information to display on the status bar. However, when the user clicks the notification icon on the status bar, what detailed information should we show the user?
This is yet to be created. This is done by calling the method setLatestEventInfo() on the notification object.

 Get a handle to the NotificationManager:
        
private NotificationManager mNotificationManager;
 mNotificationManager = 
  (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
 
Create  notification object along with properties to display on the status bar: 
 
 final Notification notifyDetails = new Notification(R.drawable.android,
  "You have got a new notification!",System.currentTimeMillis()); 

Add the details that need to get displayed when the user clicks on the notification. In this case, I have created an intent to invoke the browser to show the website http://saravananandroid.blogspot.in

Context context = getApplicationContext();
 CharSequence contentTitle = "Notification Details...";
 CharSequence contentText = "Browse Android blog by clicking me";
 Intent notifyIntent = 
new Intent(android.content.Intent.ACTION_VIEW,Uri.parse
("http://saravananandroid.blogspot.in"));
 PendingIntent intent = 
         PendingIntent.getActivity(NotificationsA.this, 0, 
         notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
          
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
  

Now the stage is set. Notify.  

mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
 
      Note that all of the above actions(except getting a handle to the 
NotificationManager) are done on the click of a button Start Notification
So all the details go into the setOnClickListener() method of the button.
Similarly, the notification, for the example sake is stopped by clicking 
a cancel notification button. And the code there is :
 

mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
 
Now, we may realize that the constant SIMPLE_NOTIFICATION_ID becomes 
the way of controlling, updating, stopping a current notification 
that is started with
 the same ID.  
 
 

Sample code:

 Notification.java:

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

public class Notifications extends Activity {
   
    private NotificationManager mNotificationManager;
    private int SIMPLE_NOTFICATION_ID;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        mNotificationManager =
                (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        final Notification notifyDetails =
                new Notification(R.drawable.android,
                 "You have got a new notification!",System.currentTimeMillis());
      
        Button start = (Button)findViewById(R.id.notifyButton);
        Button cancel = (Button)findViewById(R.id.cancelButton);
       
        start.setOnClickListener(new OnClickListener() {
          
        public void onClick(View v) {
                
                Context context = getApplicationContext();
                CharSequence contentTitle =
                        "Notification Details...";
                CharSequence contentText =
                        "Browse Android blog by clicking me";
                Intent notifyIntent =
                        new Intent(android.content.Intent.ACTION_VIEW,
                             Uri.parse("http://saravananandroid.blogspot.in/"));
                PendingIntent intent =
                    PendingIntent.getActivity(Notifications.this, 0,
                    notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
              
                notifyDetails.setLatestEventInfo(context,
                                               contentTitle, contentText, intent);
                mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
            }
        });
       
        cancel.setOnClickListener(new OnClickListener() {      
            public void onClick(View v) {           
                mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
            }
        });
    }
}
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/notifyButton"
        android:text="@string/notify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
    </Button>
    <Button
        android:id="@+id/cancelButton"
        android:text="@string/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
    </Button>
</LinearLayout>

Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bogotobogo.notificationsa"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="14" />  
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Notifications"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

No comments:

Post a Comment