![](/img/trans.png)
[英]Within Android, how do I start an activity or bring to front that activity if already on stack?
[英]Android: How do I avoid starting activity which is already in stack?
讓我們試着解釋一下我的問題:我得到了一個應用程序和一個服務。 應用程序以活動A啟動。服務發送一個廣播,讓應用程序啟動活動B現在用戶啟動活動C.
現在該服務想再次啟動活動B. 但是我怎么讓他知道活動仍然在堆棧上,或者是否有一個意圖標志?
我如何避免它會啟動活動B,因為它已經在堆棧中?
我認為你需要讓你的活動B singleInstance
,如果它已經創建你不想再次創建,那么活動的啟動模式可以在清單android:launchMode
中定義,它定義了活動將如何實現。
在你的情況下使用android:launchMode="singleInstance"
您可以使用標志Intent.FLAG_ACTIVITY_NEW_TASK 。 如果活動已經在運行,它將把它帶到前面而不是創建新活動。
如果您使用此添加Intent.FLAG_ACTIVITY_CLEAR_TOP ,則將清除此堆棧中此活動之后的所有活動。
如果活動將在已經開始時位於頂部,請設置FLAG_ACTIVITY_SINGLE_TOP標志
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
mContext.startActivity(intent);
方法android:launchMode="singleInstance"
,只是向Intent
添加標志對我不起作用。 有效的是:
在活動開始的代碼中:
Intent intent = new Intent(activity, ActivityThatHasToBeStarted.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivity(intent);
在ActivityThatHasToBeStarted
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
finish();
return;
}
// Code for this creation
}
如果您不再需要第二個活動,最好完成它,然后您應該在操作結束后對第二個活動執行此操作:
startActivity(new Intent(this, FirstActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
您可以考慮使用android:launchMode="singleTop"
而不是android:launchMode="singleInstance"
關於差異的好文章
我建議您使用Intent.FLAG_ACTIVITY_CLEAR_TOP ,因為它將刪除所有從您的目標活動開始的活動。
例如:
Intent intent = new Intent(sourceActivity, Target activity);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.