【问题标题】:Android: How to save objects initialised in the Application class when the System Restarts my App ProcessAndroid:当系统重新启动我的应用程序进程时,如何保存在应用程序类中初始化的对象
【发布时间】:2023-07-03 14:47:02
【问题描述】:

在我的应用程序类中,我有一个 Object 供从启动器屏幕启动的所有活动使用。问题是,在内存不足的情况下,系统会自动重新启动我的应用程序(我可以在设置 -> 应用程序 -> 运行进程选项卡中看到)。由于它正在重新启动(一旦应用程序处于后台就会发生),我一直使用的对象被重置为空。

我的场景:

在我的 Launcher Activity 中,我点击 DB 并在线程中获取值并使用 Setter 和 Getter 我在 Application 类中设置 Object 值。

设置后,我将从那里移动到四个活动 A(Launcher) -> B -> C -> D

现在我正在后台运行,我的设备在低内存中运行,此时我的进程被终止并重新启动(即在后台)。

在重新启动时,我的对象被重置为 null,现在如果我从最近列表或通过启动器启动我的应用程序,它仍然会启动我在上述情况下进入后台的最后一个 Activity,它是 Activity D,我在哪里正在访问抛出空指针的对象。

我的问题是,

  1. 当系统杀死它时,有什么方法可以在应用程序类级别保存对象(就像我们在 Activity onSaveInstanceState 中所做的那样)。

【问题讨论】:

    标签: android application-restart low-memory


    【解决方案1】:

    您可以使用共享首选项来保存有关对象的数据,以便重建它。 (您也可以使用数据库、本地文件等)。

    但是,如果我可以稍微偏离一下具体问题:您知道为什么您的应用程序会因为内存原因而被终止吗?您的目标是真正的低端设备或硬件吗?或者,也许您的应用程序需要进行一些优化以节省/重用内存?

    【讨论】:

      【解决方案2】:

      您保存对象的最后状态 onSaveInstanceState 并返回 onRestoreInstanceState 您可以在this best practice 中找到有关重新创建 Activity 的所有信息。我建议你阅读Activity Life Cycle

      @Override
      public void onSaveInstanceState(Bundle savedInstanceState) {
          // Save the user's current game state
          savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
          savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
      
          // Always call the superclass so it can save the view hierarchy state
          super.onSaveInstanceState(savedInstanceState);
      }
      
      @Override
      public void onRestoreInstanceState(Bundle savedInstanceState) {
          // Always call the superclass so it can restore the view hierarchy
          super.onRestoreInstanceState(savedInstanceState);
      
          // Restore state members from saved instance
          mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
          mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
      }
      

      【讨论】:

      • 问题是关于在进程重新启动时从 Application 子类保存数据,而不是关于 Activity 生命周期。
      最近更新 更多