单击通知后无法重新启动活动

时间:2016-05-09 16:40:33

标签: android notifications android-pendingintent

当应用从GCM收到消息时,会显示通知。

        Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_event_white_24dp)
            .setContentTitle("TheBriefPost")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

当我点击通知时,应用会打开活动但不会重新启动。问题是什么?怎么解决?

2 个答案:

答案 0 :(得分:1)

答案应该与Intent / Pending Intent的标志相关

根据PendingIntent in Official Docs 在Pending Intent中,您发送了一个标志PendingIntent.FLAG_UPDATE_CURRENT

  

表示如果描述的PendingIntent已经存在的标志,则保留它,但用其中的内容替换其额外数据   新的意图。

我想在你的情况下你需要使用PendingIntent.FLAG_CANCEL_CURRENT

  

表示如果描述的PendingIntent已经存在的标志,则应在生成新的PendingIntent之前取消当前的PendingIntent。

Activity in Official Docs 在Activity中设置标志Intent.FLAG_ACTIVITY_SINGLE_TOP

  

如果设置,如果活动已经在历史堆栈的顶部运行,则不会启动该活动。

我猜你在这里需要使用Intent.FLAG_ACTIVITY_CLEAR_TASK

  

如果在传递给Context.startActivity()的Intent中设置,则此标志将导致在活动开始之前清除与活动关联的任何现有任务。

答案 1 :(得分:0)

  

应用程序会打开活动但不会重新启动

不应该重启。 FLAG_ACTIVITY_SINGLE_TOP是" 如果设置,如果活动已经在历史堆栈的顶部运行,则不会启动该活动。"

为什么要重新启动它?处理意图数据?如果是,请在您的活动中实施onNewIntent()