溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何理解Android應(yīng)用開發(fā)中兩個(gè)運(yùn)行的Activity之間的通信

發(fā)布時(shí)間:2021-11-25 21:29:48 來源:億速云 閱讀:233 作者:柒染 欄目:移動(dòng)開發(fā)

如何理解Android應(yīng)用開發(fā)中兩個(gè)運(yùn)行的Activity之間的通信,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

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

首先,在默認(rèn)情況下,當(dāng)您通過Intent啟到一個(gè)Activity的時(shí)候,就算已經(jīng)存在一個(gè)相同的正在運(yùn)行的Activity,系統(tǒng)都會(huì)創(chuàng)建一個(gè)新的Activity實(shí)例并顯示出來。為了不讓Activity實(shí)例化多次,我們需要通過在AndroidManifest.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í)候,通過Intent啟到一個(gè)Activity,如果系統(tǒng)已經(jīng)存在一個(gè)實(shí)例,系統(tǒng)就會(huì)將請求發(fā)送到這個(gè)實(shí)例上,但這個(gè)時(shí)候,系統(tǒng)就不會(huì)再調(diào)用通常情況下我們處理請求數(shù)據(jù)的onCreate方法,而是調(diào)用onNewIntent方法,如下所示:

1protected 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ù)的方法,如下所示:

01public void onCreate(Bundle savedInstanceState) {
02  super.onCreate(savedInstanceState);
03  setContentView(R.layout.main);
04  processExtraData();
05}
06 
07protected void onNewIntent(Intent intent) {
08  super.onNewIntent(intent);
09  setIntent(intent);//must store the new intent unless getIntent() will return the old one
10  processExtraData()
11}
12 
13private void processExtraData(){
14  Intent intent = getIntent();
15  //use the data received here
16}

關(guān)于如何理解Android應(yīng)用開發(fā)中兩個(gè)運(yùn)行的Activity之間的通信問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI