【问题标题】:Android app is being killed when it keeps in background for long timeAndroid应用程序在后台长时间保持时被杀死
【发布时间】:2018-12-21 03:48:46
【问题描述】:

我的 android 应用程序在后台保持一段时间后被 Android 操作系统杀死。因此,当它重新启动时,它是一个空屏幕,因为在操作系统杀死进程时所有数据都已被清除。不幸的是,我m 不在 SQLite 或 sharedpreference 中存储任何数据。即使在应用程序被终止后,向 UI 组件显示数据的最佳方式是什么?(不幸的是,由于敏感数据/根据要求无法实现 SQLite)。

1,我观察到,每当在基本活动 oncreate 方法中发生这种情况时,我都会在 oncreate 方法中接收到 savedInstanceState。所以我只是从那里调用启动器方法,并且应用程序按预期工作。但这是完美的实现方式吗?

【问题讨论】:

  • 了解 ViewModel 类以存储活动生命周期的数据

标签: android android-savedstate android-ondestroy


【解决方案1】:

如果我理解正确,您应该对savedInstanceState 完全正确,关于保存简单状态并从中恢复。

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
// ...


@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
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    // ...
}

更多详情请参考here

【讨论】:

    【解决方案2】:

    很可能同时服务器端会话已过期。

    • onPause() 上注销用户并在onResume() 上再次登录。
    • 或使用service 保持服务器端会话处于活动状态。

    【讨论】:

    • 否。即使杀死应用程序,访问令牌仍然有效。服务器端在这方面没有任何作用。
    • 这个问题仍然无法重现......尤其是当“长时间”没有价值时。尝试检查if(savedInstanceState == null) {},然后只操作视图。
    • 它是可重现的,正如我之前所说的,Android OS 正在终止进程,而且非常随机。如果应用程序没有被杀死,那么用户可以向 UI 显示数据。
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2018-02-15
    • 2018-03-08
    • 2015-05-15
    相关资源
    最近更新 更多