我想找到一種方式,該線程可以關閉並重新啓動,而不會程序崩潰。它從一個菜單中調用,一個activity將面板設置爲它的內容視圖,我希望當在android上按下返回箭頭時,它返回到活動,然後該線程可以重新啓動,但是目前我嘗試的任何變體都會導致它墜毀在一個點或另一個:(安卓/ java線程崩潰
package SortItOut.sortitout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class Level1Panel extends SurfaceView implements
SurfaceHolder.Callback {
private Level1Thread thread;
static Bitmap background;
static int x = 0;
public Level1Panel(Context context) {
super(context);
getHolder().addCallback(this);
background = BitmapFactory.decodeResource(getResources(), R.drawable.gamebackground);
thread = new Level1Thread(getHolder(), this);
setFocusable(true);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
thread.stop();
}
public void render(Canvas canvas)
{
canvas.drawBitmap(background, x, 0, null);
x = x + 20;
}
}
======主題=======
package SortItOut.sortitout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class Level1Thread extends Thread {
private boolean running;
private SurfaceHolder surfaceHolder;
private Level1Panel gamePanel;
public void setRunning(boolean running) {
this.running = running;
}
public Level1Thread(SurfaceHolder surfaceHolder, Level1Panel gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.gamePanel.render(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
你會得到某種異常嗎? – Kiril