【问题标题】:How to restore activity after being stopped?停止后如何恢复活动?
【发布时间】:2014-05-02 15:20:39
【问题描述】:

场景是这样的: 我有一个启动线程的活动(通过 AsyncTask)。在更改屏幕方向(使用 onSaveInstanceState 和 onRestoreInstanceState)时,我得到了正确保存和恢复的状态,线程在 onStop() 中停止。但是,如果我“最小化”(或更改应用程序)我会保存我的状态但不会恢复。我能做什么?

-- 编辑:已解决 谢谢你们,我找到了许多类似的答案,但问题有点复杂,我认为一个简单的问题可能会导致另一种解决方案,但我想我被这两个选项卡住了。 onRestoreInstanceState 和 SharedPreferences。 谢谢!

【问题讨论】:

    标签: android android-activity restore


    【解决方案1】:

    由于保存和恢复状态的规则取决于您无法轻易预测的情况,因此我建议您使用不同的方法。使用共享偏好可能是最简单的。这是存储选项参考页面的link,其中显示了如何执行此操作。

    【讨论】:

      【解决方案2】:

      兄弟,有两种方法可以解决它。第一个非常容易。使用onSaveInstanceState()onRestoreInstanceState() 来维护您的活动。第二种方法是使用 SharedPreferences :)

      【讨论】:

        【解决方案3】:

        您需要覆盖onSaveInstanceState(Bundle savedInstanceState) 并将您想要更改的应用程序状态值写入Bundle 参数,如下所示:

        @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {
          super.onSaveInstanceState(savedInstanceState);
          // Save UI state changes to the savedInstanceState.
          // This bundle will be passed to onCreate if the process is
          // killed and restarted.
          savedInstanceState.putBoolean("MyBoolean", true);
          savedInstanceState.putDouble("myDouble", 1.9);
          savedInstanceState.putInt("MyInt", 1);
          savedInstanceState.putString("MyString", "Welcome back to Android");
          // etc.
        }
        

        Bundle 本质上是一种存储 NVP(“名称-值对”)映射的方式,它会传递给 onCreate() 和 onRestoreInstanceState(),您可以在其中提取如下值:

        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState) {
          super.onRestoreInstanceState(savedInstanceState);
          // Restore UI state from the savedInstanceState.
          // This bundle has also been passed to onCreate.
          boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
          double myDouble = savedInstanceState.getDouble("myDouble");
          int myInt = savedInstanceState.getInt("MyInt");
          String myString = savedInstanceState.getString("MyString");
        }
        

        您通常会使用这种技术来存储应用程序的实例值(选择、未保存的文本等)。

        小心:官方文档指出,您应该将重要信息保存在 onPause-Method 中,因为 onsaveinstance-method 不是 android 生命周期的一部分。 developer.android.com/reference/android/app/Activity.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-10
          相关资源
          最近更新 更多