Notification Demo in Android Marshmallow : Part 1

2 min read

Dear Friends

So we are planning to develop an android project in which whenever a user reaches to a place near a GEOFence object we already created , our android application will throw a notification to user.
This notification will be visible in User notification Bar.

User can touch this notification and can enter into the application. We will keep our discussion narrow so that we don’t fall into analysis paralysis. For more information on other blogs or material please visit android section of my blogs. Definitely you will find something of use.

So as you might have heard when we develop an android application we develop in separate modules. First module in the series would be Notification . The best way to learn android programming is to develop a simple demo android application to check a functionality. Later on when we will have a good hold over the subject we can use this functionality in our existing application.

Notification Demo for android

Please have a look at below service class

package in.relsellglobal.androidnotificationsdemo;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;


public class MyService extends Service{

    TimerNotificationTask timerNotificationTask;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        timerNotificationTask = new TimerNotificationTask();
        if(timerNotificationTask != null) {
            timerNotificationTask.execute();
        }

        return START_NOT_STICKY;

    }

    public class TimerNotificationTask extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {

            while(!isCancelled()) {
                showAndUpadateNotification("Notification Demo By Relsell","Notification Message");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }

    public void cancelNoticationTimer() {
        if(timerNotificationTask != null && !timerNotificationTask.isCancelled()) {
            timerNotificationTask.cancel(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelNoticationTimer();
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1);
    }



    public int showAndUpadateNotification(String notificationTitle, String notificationMessage) {
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());

        String[] arrNotificationMessage = notificationMessage.split(".");


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


            mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                    .setColor(Color.parseColor("#9BA947"))
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationMessage)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage));

        } else {

            mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationMessage)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage));
        }


        mBuilder.setAutoCancel(true);


        // Below is the target activity which we want to launch if notication is tapped in dropdown panel

        Intent resultIntent = new Intent(getApplicationContext(), MyService.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        mNotificationManager.notify(1, mBuilder.build());
        return 1;
    }

}

* For beginner I would like to tell a service is a component of android application that remains alive even if activity that started it has got vanished. ( Right now you need to know this only )for more details regarding services you can have a look at my blog Link would be updated soon.

So when this service is started . it starts an Asynctask (link to be updated) which offloads the task to a different thread , and frees the UI Thread (link to be updated) to do some cooler things.

Please pay attention to below code to show notification

public int showAndUpadateNotification(String notificationTitle, String notificationMessage) {
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());

    String[] arrNotificationMessage = notificationMessage.split(".");


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


        mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setColor(Color.parseColor("#9BA947"))
                .setContentTitle(notificationTitle)
                .setContentText(notificationMessage)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage));

    } else {

        mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(notificationTitle)
                .setContentText(notificationMessage)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage));
    }


    mBuilder.setAutoCancel(true);


    // Below is the target activity which we want to launch if notication is tapped in dropdown panel

    Intent resultIntent = new Intent(getApplicationContext(), MyService.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);

    mNotificationManager.notify(1, mBuilder.build());
    return 1;
}

So now you know notification can be raised as per your requirements.

This notification will be raised in a loop that iterates every 5 sec. Also when you tap on notification you or user will again reach to the Main Screen of application.


Code Example : AndroidNotificationsDemo

if you have query regarding the blog , please share your query in Google form

Happy coding! Meet you soon.