Android lock screen behaviour

烂漫一生 提交于 2020-01-17 04:40:09

问题


If I press home and come back to my app a little later I will find that the state has been preserved perfectly. For some reason however if I lock the phone and then unlock it, my app has been returned to the original state bar a few things here and there. When I looked into the logs I found that onCreate had been called while the phone was in a locked state. Because locking the phone is quite an off hand thing to do, having your game reset every time you do so is not desirable to the user. How can this be avoided at least for a longer period of time than a few seconds after locking the phone?


回答1:


This is how Android OS works, it decides by it's own when to destroy your view. To avoid loosing this information there is a Method that can be reimplemented in your activity

@Override
public void onSaveInstanceState(Bundle outState){
    iGameContent.saveGame(outState);
}

Save all your needed data into outState, and in the onCreate method, check if its a new instance or saved instance, like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    if (savedInstanceState!=null){
        iGameContent.loadGame(savedInstanceState);
    }else{
        // Normal initialization
    }
}

An example of the save/load to a Bundle is the following:

public void loadGame(Bundle aBundle){
    iBadsHit = aBundle.getInt("iBadsHits",0);
}

public void saveGame(Bundle aBundle){
aBundle.putInt("iBadsHit", iBadsHit);
}



回答2:


If your log is showing that onCreate has been called then that means your apps process was killed.

Do you know the Android Activity Lifecycle? If not, read up on it here: Android Activities




回答3:


The behavior on screen lock could vary from one device to other. Some events could cause the destruction of the app. You can try to handle some of this events to avoid this situation specifying it on the AndroidManifest.xml:

android:configChanges="keyboardHidden|orientation"

These two are the most problematic in screen lock. Yo can find more information on the last chapter of this nvidia document



来源:https://stackoverflow.com/questions/8639133/android-lock-screen-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!