How can i open Activity when notification click

John Lesh picture John Lesh · Feb 3, 2017 · Viewed 9.5k times · Source

I need use notification with click event, i have notification method but this method don't open my activity.

My code:

 private void sendNotification(String msg) {

        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
        .setContentTitle("EXX")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg)          
        .setOngoing(true);          
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}    

is this possible,

thanks.

Answer

Umesh Sonawane picture Umesh Sonawane · Feb 3, 2017

Hey @John it's very simple

you just have to do

 Intent intent = new Intent(this, ResultActivity.class);

... // Because clicking the notification opens a new ("special") activity, there's // no need to create an artificial back stack.

PendingIntent pendingIntent = TaskStackBuilder.create(getApp())
            .addNextIntent(intent)
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

And set pending Intent in mBuilder

private void sendNotification(String msg) {
        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
        .setContentTitle("EXX")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg)          
        .setOngoing(true);    
        .setContentIntent(pendingIntent)
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
} 

and you done :)