问题
When using Microsft Exchange, Android activates its password screen wich the user needs to pass every time the device is turned on.
I am making a game which is using SurfaceView run by a thread. I am using many static variables. If the device is turned off while playing, when I come back and enter the password, the game screen shows but with some bitmaps having wrong size and is frozen.
In logs I see first NullPointerException with the non-UI thread then ANR error later. It looks like the turning the device off has destroyed some objects of my application yet it did not go through onCreate and the SurfaceView constructor again when it came back.
I have no problems when pausing the game with a phonecall or clicking HOME button. Also on two other devices the game works fine after turing them off and on in the middle of the play, but they don't have the security screen.
I am using Galaxy Tab, os 2.2
EDIT: After printing a stacktrace in the thread, I get
android.graphics.Canvas.throwIfRecycled
It seems that some of my bitmaps have been recycled. Any idea how to detect this in onResume or in surfaceChanged() which always fire on returning to the application?
回答1:
At the moment my solution to this problem is to close this activity if it is not resumed with the right sequence of events. If onSurfaceChanged happens without onSurfaceCreated happening first, then close this activity. The state of the game can still be preserved and when the player relaunch this activity it will continue where it stopped.
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
//if it does not start through surfaceCreated close activity
// because some bitmaps could be recycled and crash the application
if (!surfaceCreatedFirst){
_thread.setRunning(false); //stop the thread
((Activity) context1).finish(); //close activity
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
surfaceCreatedFirst = true;
_thread = new FootballThread(holder, this);
_thread.setRunning(true);
_thread.start();
}
来源:https://stackoverflow.com/questions/5637688/game-crashing-when-devices-password-screen-enabled