从通知中调用应用程序会重新创建活动

时间:2014-09-18 21:47:22

标签: android

我想在用户从通知中调用应用程序时恢复主要活动,但此代码正在重新创建主要活动。如何阻止它?

    int mId=1;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setContentTitle("My notification")
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.twitter)
            .setContentText("Hello World!")
            .setNumber(15);
    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.setAction(Intent.ACTION_MAIN);
    resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mId, mBuilder.build());

此外,我将android:launchMode="singleTop"放置在我的清单文件中的主要活动中。如何解决此问题?

1 个答案:

答案 0 :(得分:0)

对于我的应用,我使用此代码执行此操作:

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

在清单中,我将MainActivity的午餐模式设置为singleTask android:launchMode="singleTask"