手动保存和恢复 Activity 的实例状态

Save and restore instance state of an Activity manually

我的应用程序中有一个下载 activity,用户可以在其中下载一些内容。 activity 从主 activity 调用,并检索可通过网络下载的文件列表。

为了避免在重新创建下载 activity 时再次获取整个列表,例如由于旋转,我重写 onSaveInstanceState() 以将列表存储在 Bundle 中并计算传递给 onCreate() 方法的 Bundle。这很适合旋转。

但是,如果用户点击“返回”然后 returns 下载 activity,我希望能够实现相同的行为。 Android 在这种情况下不会调用 onSaveInstanceState(),因此不会保存任何内容。

我的想法是覆盖 onBackPressed() 并包含对 onSaveInstanceState().

的调用

更新:

只需添加

@Override
public void onBackPressed() {
    onSaveInstanceState(new Bundle());
    super.onBackPressed();
}

给我以下异常:

java.lang.IllegalStateException: onSaveInstanceState

后无法执行此操作

用于 onBackPressed() 的调用。 (交换两条线没有任何作用,大概是因为没有什么可以保存了。)

Will this work at all?

没有

Will Android store the bundle and pass it to onCreate() for the next instance of the Activity it creates

没有

do I have to take care myself of storing the Bundle and passing it to the new instance (if so, how)?

没有

将您的模型数据存储在文件或数据库中,使用进程级缓存(例如,自定义单例)以最小化磁盘I/O。在可用的情况下从缓存中加载数据,或者在需要时从磁盘重新加载数据。

我终于想出了下面描述的解决方案。

用法说明:这会将下载状态 activity 保存在主内存中,它将占用 space。此外,Android 可能会随时终止后台应用程序,通常是在内存不足的情况下。如果发生这种情况,状态信息将丢失。

对于我的特定用例,我决定我可以忍受这些限制:我的应用程序写入的状态信息在千字节范围内,如果状态信息丢失,可以重新创建(只是需要时间来恢复)从服务器获取列表)。 YMMV.

在下载activity的onStop()方法中,执行:

Bundle outState = new Bundle();
this.onSaveInstanceState(outState);

outState保存在需要时可以取回的地方。在我的例子中,处理下载管理器事件的 BroadcastReceiver 是放置它的地方。

要从 BroadcastReceiver 调出 Activity,请执行以下操作:

Intent downloadIntent = new Intent(context, DownloadActivity.class);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
downloadIntent.putExtra("savedInstanceState", savedInstanceState);
context.startActivity(downloadIntent);

在下载activity的onCreate()方法中,执行:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle state = savedInstanceState;
    if (state == null)
        state = this.getIntent().getBundleExtra(Const.KEY_SAVED_INSTANCE_STATE);
    super.onCreate(state);
}