gpt4 book ai didi

java - 启动我的 android 应用程序时出现奇怪的延迟

转载 作者:行者123 更新时间:2023-11-30 03:28:12 26 4
gpt4 key购买 nike

我应该警告你我是 android 开发的新手。

问题:我的应用程序启动后出现黑屏,几秒钟后,它开始绘制我需要的内容。我已经检查绘图线程已经启动,并且已经绘制了几次内容,但是屏幕仍然是黑色的:(

我错过了什么?

这是我的代码:

Activity

public class MainActivity extends Activity {
protected SurfaceView surface;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

surface = new GameSurfaceView(this);
setContentView(surface);
}
}

表面 View

public class GameSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

protected DrawThread drawThread;

public GameSurfaceView(Context context) {
super(context);

getHolder().addCallback(this);

}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
drawThread = new DrawThread(getHolder());
drawThread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
drawThread.interrupt();
}

}

画线

public class DrawThread extends Thread {
public static final long FPS = 30;

protected SurfaceHolder surfaceHolder;

public DrawThread(SurfaceHolder surfaceHolder) {
super();
this.surfaceHolder = surfaceHolder;
}

@Override
public void run() {
while (!isInterrupted()) {
Canvas canvas = null;
try {

long renderStartedAt = SystemClock.elapsedRealtime();

canvas = surfaceHolder.lockCanvas();

if (canvas != null) {
canvas.drawColor(Color.CYAN);
// TODO DRAW
}

long duration = (1000 - (SystemClock.elapsedRealtime() - renderStartedAt) * FPS) / FPS;
if (duration > 0) {
sleep(duration);
}
} catch (InterruptedException e) {
interrupt();
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}

最佳答案

我找到了我的问题的解决方案! unlockCanvasAndPost() 不会向 SurfaceView 发送无效消息,因此只需在 unlockCanvasAndPost() 之后添加 surface.postInvalidate() 即可修复启动延迟。

关于java - 启动我的 android 应用程序时出现奇怪的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17901831/

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