while(true) 遊戲循環在 Activity finish() 後仍在運行,導致內存洩漏、崩潰。
public class GameView extends SurfaceView implements Runnable {
private volatile boolean running = true; // volatile 保證跨線程可見
@Override
public void run() {
while (running) {
Canvas canvas = holder.lockCanvas();
if (canvas != null) {
// 繪製邏輯...
holder.unlockCanvasAndPost(canvas);
}
}
}
public void stopGame() {
running = false;
}
}
@Override
protected void onPause() {
super.onPause();
gameView.stopGame(); // 設置標誌位,循環自然退出
}
@Override
protected void onDestroy() {
super.onDestroy();
gameView.stopGame(); // 雙重保險
}
private Thread gameThread;
public void startGame() {
running = true;
gameThread = new Thread(this);
gameThread.start();
}
public void stopGame() {
running = false;
try {
gameThread.join(2000); // 最多等待 2 秒
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
volatile 確保主線程修改 running 立即對渲染線程可見。onPause/onDestroy 停止線程,避免 Activity 銷毀後線程持有引用。