在Android上单击主页或返回按钮后,我在重新启动游戏时遇到问题。
我在线程中找到了部分解决方案: Android crash when app is closed and rebooted,但重启后游戏无法正常运行。它只显示也会移动但不读取触摸的图像/精灵。
//这是在游戏视图中
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) { // ce se spremeni zaslon
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
start();
}
public void start() {
loop.setRunning(true);
if (!mGameIsRunning) {
loop.start();
mGameIsRunning = true;
} else {
loop.onResume();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
loop.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
//这是游戏线程
while (running) {
canvas = null;
try{
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0;
this.gameView.update();
this.gameView.render(canvas);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0){
try{
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
} finally {
if (canvas != null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
谁能告诉我是否有任何错误或任何其他解决方案。
感谢帮助。
或者如果有人能告诉我一个停止游戏并重新启动它的好方法,好吗?
我修复了它,以便在我回家时它可以工作,但是当我回击并重新启动它时,我得到黑屏。
// 当前游戏视图代码
public void surfaceCreated(SurfaceHolder holder) {
if (loop==null)
loop = new GameLoop(getHolder(), this);
if(loop.getState() == Thread.State.TERMINATED)
{
loop = new GameLoop(getHolder(), this);
}
start();
}
public void start() {
if (!mGameIsRunning) {
mGameIsRunning = true;
loop.setRunning(true);
loop.start();
} else {
loop.onResume();
loop.start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
loop.onPause();
}
我感觉问题出在surfaceDestroy
方法上,但我不确定,因为我不知道按 Home 键或返回键有什么区别。