在开发中,我们经常会在AndroidManifest.xml中指定Activity的加载模式为singleInstance,方式如下:
- <activity android:name="ImgInfo" android:label="@string/app_name"
- android:screenOrientation="portrait" android:launchMode="singleInstance">
- </activity>
用如下方式打开Activity并传递参数:
- Intent i = new Intent(this, ImgInfo.class);
- i.putExtra("id", mPhotoId);
- startActivity(i);
如果不了解singleInstance的原理,我们想当然地会在Activity ImgInfo 的onCreate方法中写下如下的代码:
- Bundle bud = getIntent().getExtras();
- if (bud != null && bud.containsKey("id")) {
- mPhotoId = bud.getInt("id");
- }
传递不同的id,你就会发现除了第一次能正确接收之外,其他的好像都不行了。需要怎么做呢?重写onNewIntent方法,基本代码如下:
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- setIntent(intent);
- InitArg();
- }
- private InitArg(){
- Bundle bud = getIntent().getExtras();
- if (bud != null && bud.containsKey("id")) {
- mPhotoId = bud.getInt("id");
- }
- //其他操作
- }