在Android应用程序开发的时候,从一个activity启动另一个Activity并传递一些数据到新的Activity上非常简单,但是当您需要让后台运行的Activity回到前台并传递一些数据可能就会存在一点点小问题。

创新互联成都企业网站建设服务,提供网站设计、网站建设网站开发,网站定制,建网站,网站搭建,网站设计,成都响应式网站建设公司,网页设计师打造企业风格网站,提供周到的售前咨询和贴心的售后服务。欢迎咨询做网站需要多少钱:18982081108
首先,在默认情况下,当您通过Intent启到一个Activity的时候,就算已经存在一个相同的正在运行的Activity,系统都会创建一个新的Activity实例并显示出来。为了不让Activity实例化多次,我们需要通过在AndroidManifest.xml配置activity的加载方式(launchMode)以实现单任务模式,如下所示:
1 | "@string/app_name" android:launchmode="singleTask"android:name="Activity1"> |
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 |
不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:
01 | public void onCreate(Bundle savedInstanceState) { |
02 | super.onCreate(savedInstanceState); |
03 | setContentView(R.layout.main); |
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 |
13 | private void processExtraData(){ |
14 | Intent intent = getIntent(); |
15 | //use the data received here |
【编辑推荐】
- Android学习笔记:Activity跳转
- Intent,Android应用核心探秘
- 阐述Android Intent使用整理问题
- Android Activity进行全解析
- Android Activity跳转相关操作技巧分享
文章题目:Android应用开发教程:两个运行的Activity之间的通信
URL分享:
http://cdysf.com/article/cogocgi.html