Monday, 16 May 2016

NOTIFICATION IN ANDROID

04:07

Notification:

A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time

Create and Send Notifications

You have simple way to create a notification. Follow the following steps in your application to create a notification −

Step 1 - Create Notification Builder

As a first step is to create a notification builder usingNotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties

Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following −
  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder.

Step 3 - Attach Actions

This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to anActivity in your application, where they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification

Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you callNotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

The NotificationCompat.Builder Class

The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class.
Sr.No.Constants & Description
1Notification build()
Combine all of the options that have been set and return a new Notification object.
2NotificationCompat.Builder setAutoCancel (boolean autoCancel)
Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
3NotificationCompat.Builder setContent (RemoteViews views)
Supply a custom RemoteViews to use instead of the standard one.
4NotificationCompat.Builder setContentInfo (CharSequence info)
Set the large text at the right-hand side of the notification.
5NotificationCompat.Builder setContentIntent (PendingIntent intent)
Supply a PendingIntent to send when the notification is clicked.
6NotificationCompat.Builder setContentText (CharSequence text)
Set the text (second row) of the notification, in a standard notification.
7NotificationCompat.Builder setContentTitle (CharSequence title)
Set the text (first row) of the notification, in a standard notification.
8NotificationCompat.Builder setDefaults (int defaults)
Set the default notification options that will be used.
9NotificationCompat.Builder setLargeIcon (Bitmap icon)
Set the large icon that is shown in the ticker and notification.
10NotificationCompat.Builder setNumber (int number)
Set the large number at the right-hand side of the notification.
11NotificationCompat.Builder setOngoing (boolean ongoing)
Set whether this is an ongoing notification.
12NotificationCompat.Builder setSmallIcon (int icon)
Set the small icon to use in the notification layouts.
13NotificationCompat.Builder setStyle (NotificationCompat.Style style)
Add a rich notification style to be applied at build time.
14NotificationCompat.Builder setTicker (CharSequence tickerText)
Set the text that is displayed in the status bar when the notification first arrives.
15NotificationCompat.Builder setVibrate (long[] pattern)
Set the vibration pattern to use.
16NotificationCompat.Builder setWhen (long when)
Set the time that the event occurred. Notifications in the panel are sorted by this time.

Example

Following example shows the functionality of a Android notification using aNotificationCompat.Builder Class which has been introduced in Android 4.1.


(1)write  code for notification    “MainActivity.java “ file:
package testing.om.com.notification;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;

/**
 * The entry point to the BasicNotification sample.
 */
public class   MainActivity extends  Activity {
   
/**
     * A numeric value that identifies the notification that we'll be sending.
     * This value needs to be unique within this app, but it doesn't need to be
     * unique system-wide.
     */
   
public static final int NOTIFICATION_ID = 1;

   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);

    }

   
/**
     * Send a sample notification using the NotificationCompat API.
     */
   
public void sendNotification(View view) {

       
// BEGIN_INCLUDE(build_action)
        /** Create an intent that will be fired when the user clicks the notification.
         * The intent needs to be packaged into a {@link android.app.PendingIntent} so that the
         * notification service can fire it on our behalf.
         */
       
Intent intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse(
"http://developer.android.com/reference/android/app/Notification.html"));
        PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, 0);
       
// END_INCLUDE(build_action)

        // BEGIN_INCLUDE (build_notification)
        /**
         * Use NotificationCompat.Builder to set up our notification.
         */
       
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

       
/** Set the icon that will appear in the notification bar. This icon also appears
         * in the lower right hand corner of the notification itself.
         *
         * Important note: although you can use any drawable as the small icon, Android
         * design guidelines state that the icon should be simple and monochrome. Full-color
         * bitmaps or busy images don't render well on smaller screens and can end up
         * confusing the user.
         */
       
builder.setSmallIcon(R.drawable.ic_launcher);

       
// Set the intent that will fire when the user taps the notification.
       
builder.setContentIntent(pendingIntent);

       
// Set the notification to auto-cancel. This means that the notification will disappear
        // after the user taps it, rather than remaining until it's explicitly dismissed.
       
builder.setAutoCancel(true);

       
/**
         *Build the notification's appearance.
         * Set the large icon, which appears on the left of the notification. In this
         * sample we'll set the large icon to be the same as our app icon. The app icon is a
         * reasonable default if you don't have anything more compelling to use as an icon.
         */
       
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));

       
/**
         * Set the text of the notification. This sample sets the three most commononly used
         * text areas:
         * 1. The content title, which appears in large type at the top of the notification
         * 2. The content text, which appears in smaller text below the title
         * 3. The subtext, which appears under the text on newer devices. Devices running
         *    versions of Android prior to 4.2 will ignore this field, so don't use it for
         *    anything vital!
         */
       
builder.setContentTitle("BasicNotifications Sample");
        builder.setContentText(
"Time to learn about notifications!");
        builder.setSubText(
"Tap to view documentation about notifications.");

       
// END_INCLUDE (build_notification)

        // BEGIN_INCLUDE(send_notification)
        /**
         * Send the notification. This will immediately display the notification icon in the
         * notification bar.
         */
       
NotificationManager notificationManager = (NotificationManager) getSystemService(
               
NOTIFICATION_SERVICE);
        notificationManager.notify(
NOTIFICATION_ID, builder.build());
       
// END_INCLUDE(send_notification)
   
}
}



(2)write code for  activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:fitsSystemWindows="true"

    tools:context=".MainActivity">



    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">



        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"

            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />



    </android.support.design.widget.AppBarLayout>



    <include layout="@layout/content_main" />



    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"

        android:src="@android:drawable/ic_dialog_email" />



</android.support.design.widget.CoordinatorLayout>

(3)write  code for content_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:showIn="@layout/activity_main" tools:context=".MainActivity">



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="hello world"

        android:id="@+id/description"

        android:scrollbars="vertical"

        android:layout_gravity="fill_vertical"

        android:layout_weight="1"/>



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Do it!"

        android:id="@+id/button1"

        android:layout_gravity="center"

        android:onClick="sendNotification"/>



    
</RelativeLayout>


Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 ANDROID TRAINING AT VISSICOMP BY OM SIR. All rights resevered. Designed by Templateism

Back To Top