題目:請簡單介紹一些Activity的四種載入模式。
分析:四種載入模式分別為standard, singleTop,singleTask,singleInstance,設定的位置在Androidmanifest.xml中Activity元素的Android:launchMode屬性。
1.standard:執行如下代碼
Intent intent = new Intent(); intent.setClass(ActA.this, ActA.class); startActivity(intent);
在棧中會產生一個新的Activity執行個體。
2.singleTop:同樣執行上述代碼,系統會檢測到棧頂已經存在滿足需要的Activity執行個體,所以將intent發送給棧頂的執行個體,而不會產生一個新的Activity執行個體。但是如果執行如下代碼的話則會產生一個新的Activity執行個體,因為棧頂不存在滿足需要的執行個體。
Intent intent = new Intent(); intent.setClass(ActA.this, ActB.class); startActivity(intent);
3.singleTask:和singleTop不同的是,每次發送intent的時候,系統會檢測整個棧來尋找滿足需要的Activity執行個體,如果存在,將intent發送給它,不存在則產生新的。
4.singleInstance:singleTask相當於是在一個應用中某一類的Activity只存在一個執行個體,大家共用這個執行個體;singleInstance相當於是多個應用共用一個Activity的執行個體。例如,一個導遊的應用中調用了地圖應用,你在導遊應用中開啟地圖介面定位到中關村,然後按Home鍵將導遊應用放到後台,然後再開啟手機上的百度地圖,會發現百度地圖此時正好被定為到了中關村,這說明此導遊應用和百度地圖共用了同一個Activity的執行個體。
下面是官方文檔中的介紹,有興趣的讀者可以查閱:
standard:The default mode, which will usually
create a new instance of the activity when it is started, though this behavior may change with the introduction of other options such
as Intent.FLAG_ACTIVITY_NEW_TASK.
singleTop:If,
when starting the activity, there is already an instance of the same activity class in the foreground that is interacting with the user, then re-use that instance.
This existing instance will receive a call toActivity.onNewIntent() with
the new Intent that is being started.
singleTask:If,
when starting the activity, there is already a task running that starts with this activity, then instead of starting a new instance the current task is brought to the
front. The existing instance will receive a call toActivity.onNewIntent() with
the new Intent that is being started, and with the Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT flag
set. This is a superset of the singleTop mode, where if there is already an instance of the activity being
started at the top of the stack, it will receive the Intent as described there (without the FLAG_ACTIVITY_BROUGHT_TO_FRONT flag set). See the Tasks
and Back Stack document for more details about tasks.
singleInstance:Only
allow one instance of this activity to ever be running. This activity gets a unique task with only itself running in it; if it is ever launched again with the
same Intent, then that task will be brought forward and its Activity.onNewIntent() method
called. If this activity tries to start a new activity, that new activity will be launched in a separate task. See the Tasks
and Back Stack document for more details about tasks.
由於筆者水平有限,給各面試題提供的思路或代碼難免會有錯誤,還請讀者批評指正。另外,熱忱歡迎讀者能夠提供更多、更好的面試題,本人將感激不盡。如有任何意見或建議,歡迎在評論中告知。
博主徐方磊對本部落格文章享有著作權。網路轉載請註明出處http://blog.csdn.net/shishengshi。整理出版物請和作者聯絡。