Activity啟動(dòng)之SingleTask和onNewIntent的用法及原理

onNewIntent調(diào)用時(shí)機(jī)

在IntentActivity中重寫下列方法:onCreate onStart onRestart onResume onPause onStop onDestroy onNewIntent
一、其他應(yīng)用發(fā)Intent,執(zhí)行下列方法:
I/@@@philn(12410): onCreate
I/@@@philn(12410): onStart
I/@@@philn(12410): onResume

發(fā)Intent的方法:
Uri uri = Uri.parse("philn://blog.163.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

二、接收Intent聲明:
<activity android:name=".IntentActivity" android:launchMode="singleTask"
android:label="@string/testname">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="philn"/>
</intent-filter>
</activity>

三、如果IntentActivity處于任務(wù)棧的頂端,也就是說(shuō)之前打開(kāi)過(guò)的Activity,現(xiàn)在處于
I/@@@philn(12410): onPause
I/@@@philn(12410): onStop 狀態(tài)的話
其他應(yīng)用再發(fā)送Intent的話,執(zhí)行順序?yàn)椋?br> I/@@@philn(12410): onNewIntent
I/@@@philn(12410): onRestart
I/@@@philn(12410): onStart
I/@@@philn(12410): onResume

在Android應(yīng)用程序開(kāi)發(fā)的時(shí)候,從一個(gè)Activity啟動(dòng)另一個(gè)Activity并傳遞一些數(shù)據(jù)到新的Activity上非常簡(jiǎn)單,但是當(dāng)您需要讓后臺(tái)運(yùn)行的Activity回到前臺(tái)并傳遞一些數(shù)據(jù)可能就會(huì)存在一點(diǎn)點(diǎn)小問(wèn)題

首先,在默認(rèn)情況下,當(dāng)您通過(guò)Intent啟到一個(gè)Activity的時(shí)候,就算已經(jīng)存在一個(gè)相同的正在運(yùn)行的Activity,系統(tǒng)都會(huì)創(chuàng)建一個(gè)新的Activity實(shí)例并顯示出來(lái)。為了不讓Activity實(shí)例化多次,我們需要通過(guò)在Android中Manifest.xml配置activity的加載方式(launchMode)以實(shí)現(xiàn)單任務(wù)模式,如下所示:

1 <activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">
2 </activity>
launchMode為singleTask的時(shí)候,通過(guò)Intent啟到一個(gè)Activity,如果系統(tǒng)已經(jīng)存在一個(gè)實(shí)例,系統(tǒng)就會(huì)將請(qǐng)求發(fā)送到這個(gè)實(shí)例上,但這個(gè)時(shí)候,系統(tǒng)就不會(huì)再調(diào)用通常情況下我們處理請(qǐng)求數(shù)據(jù)的onCreate方法,而是調(diào)用onNewIntent方法,如下所示:
1 protected void onNewIntent(Intent intent) {
2   super.onNewIntent(intent);
3   setIntent(intent);//must store the new intent unless getIntent() will return the old one
4   processExtraData();
5 }

不要忘記,系統(tǒng)可能會(huì)隨時(shí)殺掉后臺(tái)運(yùn)行的Activity,如果這一切發(fā)生,那么系統(tǒng)就會(huì)調(diào)用onCreate方法,而不調(diào)用onNewIntent方法,一個(gè)好的解決方法就是在onCreate和onNewIntent方法中調(diào)用同一個(gè)處理數(shù)據(jù)的方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容