通知点击 (Android)

Notification click (Android)

我有一个通知,是在 MainActivity 的 OnStop() 中创建的。看起来像这样:

@Override
protected void onStop() {
    super.onStop();
    if (!finish){
        Intent intent = new Intent(this, MainActivity.class);
        intent.setAction(QUIT);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        // build notification
        // the addAction re-use the same intent to keep the example short
        n  = new Notification.Builder(this)
                .setContentTitle("Still working")
                .setContentText("Still getting data")
                .setSmallIcon(R.drawable.ic)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .build();

        mNotificationManager.notify(0, n);
    }
}

它应该重新打开 MainActivity,但它正在打开一个新的 MainActivity,所以我有两个。我应该怎么做才能打开在 OnStop() 中关闭的相同 activity?

您可以将意图的标志设置为包括以下内容:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

或者简单地编辑 MainActivity 的清单条目以包括:

android:launchMode="singleTask"

有关意图和可能标记的更多信息here and more info on launch modes here