Wednesday, June 15, 2016

Android Identify Notification Tap and Go To Particular Fragment In App


Recently in one of my project there was a requirement to go to certain section of app as soon as user taps on particular notification in Android top bar. In this blog I am going to mention how to do this.

First of all you have to properly create notification object.

private static void generateNotification(Context context, String message, String type, String date) {

int icon = R.drawable.icon;

long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
Notification notification = new Notification(icon, message, when);
notification.defaults = Notification.DEFAULT_SOUND;
String title = context.getString(R.string.app_name);

Intent notificationIntent = new Intent(context.getApplicationContext(),
notificationIntent.putExtra("msg", message);
notificationIntent.putExtra("type", type);
notificationIntent.putExtra("date", date);

PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, notificationIntent, 0);
notification.contentIntent = contentIntent;

// set intent so it does not start a new activity

PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

As you can see in above code we have created notificationIntent where I have specified My fragment activity and put all the params we get in notification as extra in intent. No go to your FragmentActivity class and add following code in onCreate method.


And added following code in in your activity

public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    if(extras != null){
            // extract the extra-data in the Notification
            String msg = extras.getString("msg");
            if(isConsiderNewIntent == true){
            Log.v("GCM","GCM message is on new intent"+msg);
            String type = intent.getStringExtra("type");
            String date = intent.getStringExtra("date");
            //check type of message here and go to certain fragment.

Hope this helps you.

No comments:

Post a Comment