android生命周期

来源:互联网 发布:基恩士plc最新编程软件 编辑:程序博客网 时间:2024/06/06 03:28

首先,在默认情况下,当您通过Intent启到一个Activity的时候,就算已经存在一个相同的正在运行的Activity,系统都会创建一个新的Activity实例并显示出来。为了不让Activity实例化多次,我们需要通过在AndroidManifest.xml配置activity的加载方式(launchMode)以实现单任务模式,如下所示:

<activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1"></activity>

 


launchMode为singleTask的时候,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法,如下所示:

 

复制代码
protected void onNewIntent(Intent intent) {    super.onNewIntent(intent);    setIntent(intent);//must store the new intent unless getIntent() will return the old one    processExtraData();}
复制代码

 


不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:

复制代码
public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);    setContentView(R.layout.main);     processExtraData();    }protected void onNewIntent(Intent intent) {     super.onNewIntent(intent);    setIntent(intent);//must store the new intent unless getIntent() will return the old one     processExtraData() }
最近做项目外部跳转发现一个新问题 :
(设置:不保留进程)外部跳转到MainActivity 经过处理函数openHomework(OnCreate 和OnNewIntent()同时调用) 跳转到另外一个界面A 返回时由于activity销毁重新调用OnCreate()进入死循环(系统销毁后保留的intent与原来intent相同)
解决方案:
OnCreate中加入判断
 if (intent != null && savedInstanceState == null) 
{
  openHomework();
}
原理:由A调回MainActivity由于不保留进程OnCreate中savedInstanceState不为空 就不会再次调用openHomework
误区:如果程序MainActivity还在后台运行 这个时候外部跳到MainActivity 其实是会先调用Oncreate进行数据恢复 在调用onNewIntent 
 
0 0
原创粉丝点击