I would create a separate class that implements Runnable and do this:
public class GameLoopThread implements Runnable {
private GameView view;
private boolean running = false;
private SurfaceHolder surfaceHolder;
public GameLoopThread(GameView view) {
this.view = view;
surfaceHolder = view.getHolder();
}
@Override
public void run() {
Canvas c;
while (running) {
c = null;
try {
c = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
//draw your stuff
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
public void setRunning(boolean run) { running = run; }
}
So to create the Thread, you would do
GameLoopThread gameLoopThread = new GameLoopThread(this);
gameLoopThread.setRunning(true);
Thread t = new Thread(gameLoopThread);
And when you want to stop it:
gameLoopThread.setRunning(false);
Basically it's a custom Thread that has a way to stop it.