我试图找到一种方法,可以在没有程序崩溃的情况下关闭并重新启动线程。它是从一个菜单中调用的,一个活动将面板设置为其内容视图,我希望当在android上按下返回箭头它返回到活动然后线程可以重新启动但是当前我尝试的任何变化都会导致它在某一点崩溃:(
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);
}
}
}
}
}
答案 0 :(得分:0)
你不应该使用thred.stop();你必须允许thred通过停止循环来自行停止。
检查Surface View动画的第二个示例:{{3p>
答案 1 :(得分:0)
以下是一些建议(没有获得有关崩溃例外的任何细节):
interrupt()
线程而不是调用stop()
(中断也会使线程脱离阻塞状态)。InterruptedException
方法中的run
。我确定我错过了一些东西,但一般来说这应该让你免于麻烦。再一次,在不知道你得到的具体异常的情况下,我会假设你正在调用stop并且线程在运行时的任何状态下都没有正确清理,因此你可以在某个时刻得到崩溃(取决于什么被国家腐败了。)