Kimochis
Kimochis

Reputation: 27

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());

Upvotes: 1

Views: 696

Answers (2)

Yasin Kaçmaz
Yasin Kaçmaz

Reputation: 6663

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.

Upvotes: 1

comeback4you
comeback4you

Reputation: 716

//add intent and PendingIntent for open activity

Intent attendanceIntent = new Intent(getApplicationContext(), Details.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                attendanceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

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

Upvotes: 1

Related Questions