【问题标题】:Activity starts again when lock phone screen锁定手机屏幕时重新开始活动
【发布时间】:2015-10-20 22:29:49
【问题描述】:

我遇到了下一个问题。我正在开发一个游戏。当我从物理按钮锁定设备并解锁时,游戏又开始了。活动再次开始。当我解锁它时,我想从锁定它的那一刻起继续玩。

【问题讨论】:

    标签: android android-activity


    【解决方案1】:

    然后需要在onPause中保存状态,在onResume中再次加载

    【讨论】:

    • 是的,但是在我的活动中,我有 100 个变量,必须有一个简单的方法
    【解决方案2】:

    你需要save and restore state of your activity 使用onSaveInstanceStateonRestoreInstanceState

    save:

    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);
    }
    

    restore:

    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);
    }
    

    【讨论】:

    • 是的,但在我的活动中,我有 100 个变量,必须有一个简单的方法
    • 您可以尝试在每次更改时将变量存储到共享首选项中。再一次,即使那样也不容易。目前我想不出别的办法。推荐使用实例状态。
    • 另外,你需要仔细选择要保留的变量,如果你仔细看你可能会发现你不需要全部保留
    • 有没有办法知道 pohone 是否在 onResume 方法中被锁定和解锁?解锁手机后,我想知道要求,因为 onResume 我有一个方法可以重新开始
    • 您的意思是说您正在通过您的代码重新启动 onResume 中的所有内容? stackoverflow.com/a/11623910/1529129这可能对你有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2020-01-31
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多