兩個正在運行的activity之間的通信

 

在android應用程序開發的時候,從一個activity啓動另一個activity並傳遞一些數據到新的activity非常的簡單,但是當您需要讓後臺運行的activity回到前臺並傳遞一些數據可能就會存在一點點小問題。

首先,在默認情況下,當您通過intent啓到一個activity的時候,就算已經存在一個相同的正在運行的activity,系統都會創建一個新的activity實例並顯示出來。爲了不讓activity實例化多次,我們需要通過在AndroidManifest.xml配置activity的加載方式(launchMode)以實現單任務模式,如下所示:

1 <ACTIVITY android:name="Activity1" android:launchmode="singleTask" android:label="@string/app_name">
2 </ACTIVITY>

launchMode爲singleTask的時候,通過intent啓到一個activity,如果系統已經存在一個實例,系統就會將請求發送到這個實例上,但這個時候,系統就不會再調用通常情況下我們處理請求數據的onCreate方法,而是調用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 }

 不要忘記,系統可能會隨時殺掉後臺運行的activity,如果這一切發生,那麼系統就會調用onCreate方法,而不調用onNewIntent方法,一個好的解決方法就是在onCreate和onNewIntent方法中調用同一個處理數據的方法,如下所示:

01 public void onCreate(Bundle savedInstanceState) {
02   super.onCreate(savedInstanceState);
03   setContentView(R.layout.main);
04   processExtraData();
05 }
06   
07 protected 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   
13 private void processExtraData(){
14   Intent intent = getIntent();
15   //use the data received here
16 }
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章