gpt4 book ai didi

java - thread.sleep(long millis) 在 Android 中不起作用

转载 作者:行者123 更新时间:2023-12-02 11:53:10 25 4
gpt4 key购买 nike

我想在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();
}
}

最佳答案

它不是“不工作” - 但它可能会抛出一个 InterruptedException,您要么必须声明抛出该异常(在方法签名中抛出 InterruptedException),要么您应该捕获它:

try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

PS:sleep是一个静态方法,应该以静态方式调用:Thread.sleep而不是thread.sleep

关于java - thread.sleep(long millis) 在 Android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47750101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com