当通知被点击时如何打开Activity

5
我需要使用带有点击事件的通知,我有通知方法,但这个方法不能打开我的活动。
我的代码:
 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());
}    

这是可能的吗,谢谢。

3
可能是 打开通知后打开应用程序 的重复问题。 - Murat Karagöz
不是重复的。OP只是没有设置setContentIntent() - David Wasser
2个回答

7

是的,这是可能的。

改变你的方法,像这样:

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

并添加你的MainActivity

    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

这段代码能正常运行。

哦,谢谢!这段代码对我有用!我爱你兄弟 <3 - John Lesh
请注意,addAction(getNotificationIcon(), "Action Button", pIntent)已被弃用。 - Moussa

7

嘿 @John,这很简单

你只需要做以下事情:

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

由于点击通知会打开一个新的(“特殊”)活动,因此不需要创建人工返回栈。

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

并在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());
} 

完成了 :)

可以使用MainActivity.class或特定的活动名称来指定您的活动名称,而不是使用getApp() - greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接