四中启动模式以及onNewIntent(Intent intent)

来源:互联网 发布:淘宝升级企业店铺坏处 编辑:程序博客网 时间:2024/06/07 05:03

熊猫猫韩国代购

Activity启动模式设置:
        <activity android:name=".MainActivity" android:launchMode="standard" />

Activity的四种启动模式:
. standard
        模式启动模式,每次激活Activity时都会创建Activity,并放入任务栈中。

. singleTop
        如果在任务的栈顶正好存在该Activity的实例, 就重用该实例,否者就会创建新的实例并放入栈顶(即使栈中已经存在该Activity实例,只要不在栈顶,都会创建实例)。

. singleTask
        如果在栈中已经有该Activity的实例,就重用该实例(会调用实例的onNewIntent())。重用时,会让该实例回到栈顶,因此在它上面的实例将会被移除栈。如果栈中不存在该实例,将会创建新的实例放入栈中。 

. singleInstance
        在一个新栈中创建该Activity实例,并让多个应用共享改栈中的该Activity实例。一旦改模式的Activity的实例存在于某个栈中,任何应用再激活改Activity时都会重用该栈中的实例,其效果相当于多个应用程序共享一个应用,不管谁激活该Activity都会进入同一个应用中。

首先,在默认情况下,当您通过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()

}

private void processExtraData(){

Intent intent = getIntent();

//use the data received here

}
复制代码


原创粉丝点击