Android - 为什么使用 onSaveInsanceState() 来保存未调用的位图对象?

标签 android bitmap savestate

我正在制作一个简单的绘图应用程序。

我希望能够在设备方向改变时保存用户在屏幕上的绘图。这只发生在主要 Activity 中。

我读到,如果方向发生变化,那么 Activity 将被销毁并再次重新创建(onCreate(Bundle created) 被调用)。 我不确定这是否意味着它也应该调用 onSavedInstanceState(Bundle bundle),因为在我的应用程序中,只有当另一个 Activity 将焦点放在我的主要 Activity 之上时才会调用它,而不是当旋转到横向/纵向。

我只是在寻找一种方法来保存现有位图,并在方向发生变化时将其传递给主要 Activity 。如果我的 onSaveInstanceState 从未被调用,我该怎么办?

此外,由于 Bitmap 实现了 parceable,我已经使用了它。

这是主要 Activity 的代码:

 public void onCreate(Bundle savedInstanceState) {      
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
// some more activity code...

        if (savedInstanceState != null) {
        bitmap = savedInstanceState.getParcelable("bitmap");
        Log.d("STATE-RESTORE", "bitmap created");
        paintBoard.setBitmapBackground(bitmap, false);
        Log.d("RESTORING...", "onRestoreInstanceState()");
    } else {
        Log.d("SavedInstanceState", "null");
    }
}


// Never called when I change orientation on my device
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    bitmap = Bitmap.createBitmap(paintBoard.getBitmap());
    outState.putParcelable("bitmap", bitmap);
    Log.d("STATE-SAVE", "onSaveInstanceState()");
}

我们将不胜感激。

编辑:

我从 AndroidManifest.xml 文件中删除了这一行:

android:configChanges="orientation"

现在 onSaveInstanceState() 在我改变设备方向时会被调用。

最佳答案

你应该阅读 this article完全。

...it might not be possible for you to completely restore your activity state with the Bundle that the system saves for you with the onSaveInstanceState() callback—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. In such a situation, you can alleviate the burden of reinitializing your activity by retaining a stateful Object when your activity is restarted due to a configuration change.

To retain an object during a runtime configuration change:

  1. Override the onRetainNonConfigurationInstance() method to return the object you would like to retain.
  2. When your activity is created again, call getLastNonConfigurationInstance() to recover your object.

关于Android - 为什么使用 onSaveInsanceState() 来保存未调用的位图对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346275/

相关文章:

android - Android App连接SQL Server数据库的方法

android - 发布带有广告的 Android 应用

java - 使用 MediaRecorder 将 View 中的位图编码为视频

设备关闭或电池耗尽时的 iOS 保存状态

php - 如何在 php 中暂停执行、保存状态并稍后从同一点继续?

java - 为什么使用 onPrepareOptionsMenu 创建一个布局文件出现在屏幕顶部但运行时出现在底部的菜单?

android - 如何使用 Surfaceholder 在 Android 的 Portitate 模式下更改保存图像方向

java - Android - Android 中的屏幕旋转和位图错误

android - Vector Drawables 与 RAM 方面的位图 (Android)

java - Android:返回 Activity 时如何在EditText中保存值