已公开活动已从通知中打开

时间:2015-04-20 07:16:44

标签: android android-notifications android-alarms

我通过通知创建一个警报,但是当我通过通知打开MainActivity时,另一个MainActivity会打开,而如果我关闭MainActivity,则会有另一个MainActivity。

这是我的BroadcastReceiver的代码:

    @Override
    public void onReceive(Context context, Intent intent)
    {

        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context,
                        0, notificationIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT);

         NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context);
         mBuilder.setContentIntent(contentIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("E' ora di colazione!")
                    .setContentText("Cosa c'è per colazione?")
                    .setAutoCancel(true);


                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, mBuilder.build());


    }   

}

3 个答案:

答案 0 :(得分:1)

Menifest.xml

的活动代码中添加 android:launchMode =“singleTask”

您的Activity类中的@Override onNewIntent

你的班级将在onNewIntent()中获得新的意图并继续你想做的任何事情。

@Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
    }

答案 1 :(得分:0)

更新您的意图创建代码

将以下标志添加到意图FLAG_ACTIVITY_REORDER_TO_FRONT

Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

答案 2 :(得分:0)

我使用notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

找到了解决方案
@Override
    public void onReceive(Context context, Intent intent)
    {

        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context,
                        0, notificationIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT);

         NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context);
         mBuilder.setContentIntent(contentIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("E' ora di colazione!")
                    .setContentText("Cosa c'è per colazione?")
                    .setAutoCancel(true);


                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, mBuilder.build());


    }