How can i open Activity when notification click

倾然丶 夕夏残阳落幕 提交于 2020-08-25 08:05:06

问题


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.


回答1:


Yes, it is possible.

Change Your method, like that;

private void sendNotification(String msg) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("yourpackage.notifyId", NOTIFICATION_ID);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
            .setContentTitle("EXX")
            .setSmallIcon(R.drawable.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle()
            .bigText(msg))
            .addAction(getNotificationIcon(), "Action Button", pIntent)
            .setContentIntent(pIntent)
            .setContentText(msg)
            .setOngoing(true);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

and add your mainactivity

    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

this code working.




回答2:


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 :)



来源:https://stackoverflow.com/questions/42026431/how-can-i-open-activity-when-notification-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!