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
.getSystemService(Context.NOTIFICATION_SERVICE);
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(),
MyActivity.class);
notificationIntent.putExtra(“msg”, message);
notificationIntent.putExtra(“type”, type);
notificationIntent.putExtra(“date”, date);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
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.