如果已暂停

时间:2016-03-01 17:02:37

标签: android android-intent android-activity notifications android-pendingintent

我运行的通知服务会为用户创建通知,如果用户点击通知会打开一个活动来显示消息,我用来创建通知的方法是:

public void createNotificationMsg(String name,String doing, boolean persistent){

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
            0, new Intent(getApplicationContext(), MessageNotificationActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP).putExtra("message", doing),
            PendingIntent.FLAG_CANCEL_CURRENT);


    NotificationCompat.Builder notificationBuilder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.my_logo_96)
                    .setContentTitle(name)
                    .setContentText(doing)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setContentIntent(pendingIntent)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setColor(Color.parseColor("#1aadce"));

    if (persistent){
        notificationBuilder.setOngoing(true);
    }
    else {
        notificationBuilder.setOngoing(false);
    }

    NotificationManagerCompat notificationManager =
            NotificationManagerCompat.from(getApplicationContext());

    Notification notification = notificationBuilder.build();

    notificationManager.notify(0, notification);
}

MessageNotificationActivity正在使用“android:style / Theme.Dialog”使它看起来像一个对话框现在的事情是,当我点击通知时一切顺利,活动打开就像一个没有任何内容的对话框后台,但如果应用程序暂停并且在我点击通知时处于后台,它会将应用程序主要活动带到前面,然后在其上打开MessageNotiicationActivity。如何使通知不会将主要活动置于前面而只是意图进行特定活动?

2 个答案:

答案 0 :(得分:1)

发生这种情况的原因是,以对话框为主题的Activity与您应用中的其他活动具有相同的"任务关联" ,因此当您点击通知时,Android寻找适当的任务来启动以对话为主题的Activity。如果您的应用在后台,Android会将其视为具有相同"任务关联性" 的任务作为对话框主题的活动,并将该任务带到前台并启动以对话为主题的活动进入该任务。

要防止这种情况发生,您需要将android:taskAffinity=""添加到清单中的<activity>声明,以用于以对话框为主题的活动。这告诉Android将以对话为主题的Activity启动到新任务中,而不是启动到应用程序的任务中。

答案 1 :(得分:0)

尝试将标志Intent.FLAG_ACTIVITY_CLEAR_TASK添加到您的意图中。这将清除任务中的任何其他活动。