前言
相信,大家都应该使用过singleTask启动模式去启动目标Activity,这模式是当任务栈中存在目标Activity实例时,是不会重新创建该Activity(即不走onCreate方法),而是销毁该Activity上面所有其他的Activity,以此来将目标Activity置于栈顶显示(此时走onResume方法);如果不存在,则在栈顶创建一个Activity实例(走onCreate方法)。而本次传参失败是发生在任务栈中已经存在目标Activity实例的情况下再次启动该Activity而传参的时候,经过一番学习,最终找到解决方案。
传参失败情况
AndroidManifest.xml声明目标Activity如下:
<activity
android:name=".activity.VerifyIDCardActivity"
android:screenOrientation="portrait"
android:launchMode="singleTask"/>
首次在A Activity(standard启动模式)中启动目标Activity(VerifyIDCardActivity)如下:
Intent intent = new Intent(this, VerifyIDCardActivity.class);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
在目标Activity的onCreate()中正常获取参数的代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_idcard);
String phone = getIntent().getStringExtra("phone");
String account = getIntent().getStringExtra("account");
}
此时在目标Activity中启动了B Activity(standard启动模式),在B Activity中又启动C Activity(standard启动模式),在C Activity中启动目标Activity(VerifyIDCardActivity)并传递和A Activity传递的key一样,但此时在目标Activity页面显示的仍然是A传递过来的值,而不是C传递过来的值。
解决方案
首先知道,singleTask启动模式是当任务栈中存在目标Activity实例时,再次启动它时是不会重新创建该Activity(即不走onCreate方法),故需要把目标Activity里获取参数的方法移到onResume里:
@Override
protected void onResume() {
super.onResume();
String phone = getIntent().getStringExtra("phone");
String account = getIntent().getStringExtra("account");
}
其次需要重写Activity的onNewIntent的方法,因为是singleTask模式 不走onCreate方法但会调用onNewIntent方法,所以在这个方法里更新我们的Intent,如:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
这样在onResume方法里就能读到最新Activity传过来的值了。