现在假设我们有Activity A ,B
activity singletask 启动模式 当此activity存在栈中 再次进入无需重新创建移除其上面的activity使其到栈顶 取用
当B的启动模式设置为singletask第一次A->B getintent 可以获取到数据,当第二次进入的时候突然获取不到了 数据是空的,为什么会这样呢,先看下上面关于singletask的介绍,我们在看下源码里面getintent方法的介绍
/**返回开始创建的activity的意图*/
/** Return the intent that started this activity. */
public Intent getIntent() {
return mIntent;
}
就是说通过getIntent获取到的是activity创建时候的意图intent,并且会把这个意图保存下来,之后如果在activity从后台调出到前台,用getIntent方法获取到的始终是之前保存的意图。
那当我们的意图发生变化的时候怎么办呢
activity的源码中紧邻着getIntent的还有个setIntent方法
/**
* Change the intent returned by {@link #getIntent}. This holds a
* reference to the given intent; it does not copy it. Often used in
* conjunction with {@link #onNewIntent}.
*
* @param newIntent The new Intent object to return from getIntent
*
* @see #getIntent
* @see #onNewIntent
*/
public void setIntent(Intent newIntent) {
mIntent = newIntent;
}
注释上说 可以通过此方法改变getintent返回的intent 经常与onNewIntent方法一起使用
好那我们在看一下onNewIntent的源码注释(渣翻译见谅)
/**
* This is called for activities that set launchMode to "singleTop" in
* their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
* flag when calling {@link #startActivity}. In either case, when the
* activity is re-launched while at the top of the activity stack instead
* of a new instance of the activity being started, onNewIntent() will be
* called on the existing instance with the Intent that was used to
* re-launch it.
*
* <p>An activity will always be paused before receiving a new intent, so
* you can count on {@link #onResume} being called after this method.
*
* <p>Note that {@link #getIntent} still returns the original Intent. You
* can use {@link #setIntent} to update it to this new Intent.
*
* @param intent The new intent that was started for the activity.
*
* @see #getIntent
* @see #setIntent
* @see #onResume
*/
protected void onNewIntent(Intent intent) {
}
大概的意思就是activity设置为singletop的时候在栈中当startactivity()通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上不会重新创建。
getintent返回之前的intent可以通过setintent改变返回的intent。此方法会在onresume之前调用
解决方法
所以当我们获取不到数据的时候只要重写onNewIntent就好
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
setIntent(intent);
super.onNewIntent(intent);
}