android onNewIntent
轉載自:http://blog.csdn.net/tyj1982/article/details/6848879
----------
在Android應用程序開發(fā)的時候,從一個Activity啟動另一個Activity并傳遞一些數(shù)據(jù)到新的Activity上非常簡單,但是當您需要讓后臺運行的Activity回到前臺并傳遞一些數(shù)據(jù)可能就會存在一點點小問題。
首先,在默認情況下,當您通過Intent啟到一個Activity的時候,就算已經(jīng)存在一個相同的正在運行的Activity,系統(tǒng)都會創(chuàng)建一個新的Activity實例并顯示出來。為了不讓Activity實例化多次,我們需要通過在AndroidManifest.xml配置activity的加載方式(launchMode)以實現(xiàn)單任務模式,如下所示:
1 <activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">
2 </activity>
launchMode為singleTask的時候,通過Intent啟到一個Activity,如果系統(tǒng)已經(jīng)存在一個實例,系統(tǒng)就會將請求發(fā)送到這個實例上,但這個時候,系統(tǒng)就不會再調(diào)用通常情況下我們處理請求數(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)可能會隨時殺掉后臺運行的Activity,如果這一切發(fā)生,那么系統(tǒng)就會調(diào)用onCreate方法,而不調(diào)用onNewIntent方法,一個好的解決方法就是在onCreate和onNewIntent方法中調(diào)用同一個處理數(shù)據(jù)的方法,如下所示:
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 }
總結
以上是生活随笔為你收集整理的android onNewIntent的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于ListView 自定义 Adapt
- 下一篇: 位运算的用途(转)