如何防止Android操作系统关闭内存的后台应用程序?

时间:2015-07-01 04:31:40

标签: android android-service

我创建了一个使用~10MB RAM的应用程序。似乎当我启动其他应用程序并且我的应用程序在后台时,它有时会关闭。我怀疑这是因为Android操作系统关闭后台应用程序以进行RAM管理(手机有1024MB的总RAM)。

有什么方法可以让我的应用程序始终以编程方式或其他方式在后台运行?

2 个答案:

答案 0 :(得分:4)

您无法在操作系统的愿望中保持您的应用程序在后台运行。您可以做的最好的事情是保存和恢复活动/片段/视图等的状态。

Recreating an Activity

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

//saving
@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);
}

//restoring
@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
    }
    ...

}

答案 1 :(得分:3)

使用服务在后台运行。

Run Background Service了解详情。