Kimochis Kimochis - 3 months ago 19
Android Question

Launch activity on click notification

I want the main activity to be launched when the notification is clicked. This is even when the user is not in the app. How do I do so?

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.diamond)
.setContentTitle("Crystallise")
.setContentText("making your thoughts crystal clear");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyID, mBuilder.build());

Answer

First of all you need PendingIntent :

Intent intent=new Intent(mContext, Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent notificationIntent= PendingIntent.getActivity(mContext,requestCode, intent,PendingIntent.FLAG_UPDATE_CURRENT);

Then in your NotificationCompat.Builder add this: .setContentIntent(notificationIntent)

For unique request code use this : int requestCode=(int)System.currentTimeMillis();

You can use this in Non Activity classes too, e.g: Service, BroadcastReceiver . Then your app will be launched even it is in closed state.