[英]Android: always launch top activity when clicked on notification
編輯 :請注意:我完全重新解釋了我的問題。
我的應用程序有兩個Activites
:A和B。 Activity
A為MAIN
。 這樣,應用程序啟動,並且A出現在屏幕上。 用戶按下按鈕,新的Activity
B出現在屏幕上。
因此,我的“ back stack”中現在有2個活動: A和B。
現在,我按“主頁”鍵,然后在啟動器上單擊我的應用程序圖標: Activity
B出現在屏幕上( 而不是A ),只要它是我任務中的首要活動即可。
現在的問題:我如何才能使Intent
同樣打開任務的當前Activity
?
我需要它在Notification
使用:當用戶單擊我的Notification
,此任務的頂部Activity
應該出現在屏幕上,而不是指定的活動。
我嘗試了許多Intent標志,例如SINGLE_TOP
和其他標志,但是我仍然無法獲得所需的東西。
有人知道解決方案嗎?
好吧,幾天后花了幾個小時,我找到了解決方案:
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
這就是啟動器啟動應用程序的方式,它對於通知Intent也很好用。
我曾經這樣。
private void notifyUser(Context context) {
notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence text = "Test Notification";
Notification notification = new Notification(R.drawable.icon, text,
System.currentTimeMillis());
Intent resultIntent = new Intent(context, StartActivity.class);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(GeneralSettingsActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "Title", text,
resultPendingIntent);
notificationManager.notify(AUTOSYNC_COMPLETED_NOTIFICATION,
notification);
}
您可以使用android:launchMode =“ singleInstance”。 可能這會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.