最近做一个连连看游戏,使用了SurfaceView画图。通常按下HOME键时,游戏界面隐藏到后台,再次点击图标进入游戏时,应该返回之前的游戏的状态。
首先要理解SurfaceView的生命周期:
(1)程序第一次启动时,调用view的构造函数->surfaceCreated->surfaceChanged
(2)按HOME键时,调用surfaceDestroyed;点击图标返回程序时,调用surfaceCreated->surfaceChanged
(3)按返回键时,调用surfaceDestroyed;点击图标返回程序时,调用view的构造函数->调用surfaceCreated->surfaceChanged
所以正确的做法是:
(1)将线程设为view的成员
(2)在surfaceCreated中把线程new出来,并设置运行标志true、调用线程的start(不要在构造函数中new)
(3)在surfaceDestroyed中将运行标志设为false
代码:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private GameViewDrawThread gameViewDrawThread;
private GameActivity activity;
public GameView(GameActivity gameActivity) {
super(gameActivity);
getHolder().addCallback(this);
this.activity = gameActivity;
}
public void surfaceCreated(SurfaceHolder holder) {
gameViewDrawThread = new GameViewDrawThread(this);
gameViewDrawThread.setRunning(true);
gameViewDrawThread.start();
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {}
public void surfaceDestroyed(SurfaceHolder holder) {
gameViewDrawThread.setRunning(false);
}
}
public class GameViewDrawThread extends Thread {
GameView gameView;
private boolean isRunning = true;
SurfaceHolder surfaceHolder;
public void setRunning(boolean bRun) {
isRunning = bRun;
}
public GameViewDrawThread(GameView gameView) {
this.gameView = gameView;
this.surfaceHolder = gameView.getHolder();
}
public void run() {
Canvas c;
while (isRunning == true) {
c = null;
try {
c = this.surfaceHolder.lockCanvas();
synchronized (this.surfaceHolder) {
gameView.doDraw(c);
}
} finally {
if (c != null) {
this.surfaceHolder.unlockCanvasAndPost(c);
}
}
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
没看懂的,可以参考http://blog.youkuaiyun.com/xiaominghimi/article/details/6149816