Search Wikipedia

Search results

Jun 24, 2015

Create and Send Notifications

There is  a simple method  to create notification. Follow the following steps to create a notification.

STEP 1 - CREATE NOTIFICATION BUILDER

As a first step is to create a notification builder using NotificationCompat.Builder.build(). We will use Notification 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 we have Builder object, we can set its Notification properties using Builder object as per our requirement. But this is mandatory to set atleast following:
  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuiler.setContentTitle("Notification Alert, Click Me !");
mBuilder.setContentText("Hi, This is Android Notification Detail");

STEP 3 - ATTACH ACTIONS

This is an optional part and required if we want to attach an action with the application. An action allows users to go directly from the notification to an Activity in our application, where user 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 our application. To asscociate the PendingIntent with a gesture, call the appropriate method of NotificationBuilder.Builder. For example, if we want to start Activity when user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

A PendingIntent object helps us to perform an action on our application's behalf, often at a later time, without caring of whether or  not our application is running.

We can help of stack builder object which will contain an artificial back stack for the started Activity. This ensure the navigating backward from the Activity leads out of our 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.setCotentIntent(resultPendingIntent);

STEP 4 - ISSUE THE NOTIFICATION

Finally, we can pass the Notification object to the system by calling NotificationManager.notifiy() to send our notification. Make sure we call NotificationCompat.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);
//notificatioID allows us to update the notification later on 
mNotificationManager.notify(notificationID, mBuilder.build());

CODE:

MainActivity.java

package sarojsubedi.com.np.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    private NotificationManager mNotifcationManager;
    private int notificationID = 100;
    private int numMessages = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startBtn = (Button) findViewById(R.id.am_start);
        final Button stopBtn = (Button) findViewById(R.id.am_cancel);
        Button updateBtn = (Button) findViewById(R.id.am_update);

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                displayNotification();
            }
        });

        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelNotification();
            }
        });

        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateNotification();
            }
        });

    }

    protected void displayNotification() {
        Log.i("Start", "notification");

        /*invoke default notification service*/
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("New message");
        mBuilder.setTicker("New Message Alert!!");
        mBuilder.setSmallIcon(android.R.drawable.arrow_up_float);

       /* increas notifiction number every time a notification  arrives*/
        mBuilder.setNumber(++numMessages);

      /*  creates an explicit itent for an activity in app*/
        Intent resultIntent = new Intent(this, NotificationView.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationView.class);

        /*adds intent that starts activity to toip of stack*/
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        mNotifcationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

       /* notificatioId allows us to update notification later on */
        mNotifcationManager.notify(notificationID, mBuilder.build());


    }

    protected void cancelNotification() {
        Log.i("Cancel", "notification");
        mNotifcationManager.cancel(notificationID);
    }

    protected void updateNotification() {
        Log.i("Update", "notification");

        /*invoke the default notification servive*/
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setContentTitle("Updated Messge");
        mBuilder.setContentText("You have got updated message");
        mBuilder.setTicker("Updated Message Alert");
        mBuilder.setSmallIcon(android.R.drawable.arrow_down_float);

        /*increase notification counter*/
        mBuilder.setNumber(++numMessages);
        /* Creates an explicit intent for an Activity in your app */
        Intent resultIntent = new Intent(this, NotificationView.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationView.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);
        mNotifcationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        /* Update the existing notification using same notification ID */
        mNotifcationManager.notify(notificationID, mBuilder.build());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml


    


NotificationView.java
package sarojsubedi.com.np.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    private NotificationManager mNotifcationManager;
    private int notificationID = 100;
    private int numMessages = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startBtn = (Button) findViewById(R.id.am_start);
        final Button stopBtn = (Button) findViewById(R.id.am_cancel);
        Button updateBtn = (Button) findViewById(R.id.am_update);

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                displayNotification();
            }
        });

        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelNotification();
            }
        });

        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateNotification();
            }
        });

    }

    protected void displayNotification() {
        Log.i("Start", "notification");

        /*invoke default notification service*/
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("New message");
        mBuilder.setTicker("New Message Alert!!");
        mBuilder.setSmallIcon(android.R.drawable.arrow_up_float);

       /* increas notifiction number every time a notification  arrives*/
        mBuilder.setNumber(++numMessages);

      /*  creates an explicit itent for an activity in app*/
        Intent resultIntent = new Intent(this, NotificationView.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationView.class);

        /*adds intent that starts activity to toip of stack*/
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        mNotifcationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

       /* notificatioId allows us to update notification later on */
        mNotifcationManager.notify(notificationID, mBuilder.build());


    }

    protected void cancelNotification() {
        Log.i("Cancel", "notification");
        mNotifcationManager.cancel(notificationID);
    }

    protected void updateNotification() {
        Log.i("Update", "notification");

        /*invoke the default notification servive*/
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setContentTitle("Updated Messge");
        mBuilder.setContentText("You have got updated message");
        mBuilder.setTicker("Updated Message Alert");
        mBuilder.setSmallIcon(android.R.drawable.arrow_down_float);

        /*increase notification counter*/
        mBuilder.setNumber(++numMessages);
        /* Creates an explicit intent for an Activity in your app */
        Intent resultIntent = new Intent(this, NotificationView.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationView.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);
        mNotifcationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        /* Update the existing notification using same notification ID */
        mNotifcationManager.notify(notificationID, mBuilder.build());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_notification_view


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"

tools:context="sarojsubedi.com.np.notificationdemo.NotificationView"/>

ScreenShots








No comments:

Post a Comment

Did this post help you? Do you have any questions? Drop your thoughts here...

}