我想在Android中做一个简单的动画。我按照本教程系列来设置基本的java代码:
https://www.youtube.com/watch?v=UH2OWnq7NQ4
为了能够控制帧速率,我添加了行thread.sleep(500);
。但是,这条线用红色加下划线,如果我在它上方悬停,它会说:
Unhandled exception: java.lang.interruptedException
我做错了什么?谢谢!
public class AnimationActivity extends SurfaceView implements Runnable {
Thread thread = null;
boolean canDraw = false;
Bitmap backgroundBlack;
Canvas canvas;
SurfaceHolder surfaceHolder;
public AnimationActivity(Context context) {
super(context);
surfaceHolder = getHolder();
backgroundBlack = BitmapFactory.decodeResource(getResources(), R.drawable.background_black);
}
@Override
public void run() {
while (canDraw) {
if (!surfaceHolder.getSurface().isValid()) {
continue;
}
canvas = surfaceHolder.lockCanvas();
canvas.drawBitmap(backgroundBlack,0,0, null);
//drawing stuff here
surfaceHolder.unlockCanvasAndPost(canvas);
thread.sleep(500)
}
}
public void pause() {
canDraw = false;
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
thread = null;
}
public void resume() {
canDraw = true;
thread = new Thread(this);
thread.start();
}
}
答案 0 :(得分:1)
它不是“不工作” - 但它可能抛出一个InterruptedException,你要么必须声明要抛出(在方法签名中抛出InterruptedException),要么你应该抓住它:
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
PS:sleep是一个静态方法,应该以静态方式调用:Thread.sleep而不是thread.sleep