1

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

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

我错过了什么?

这是我的代码:

活动

public class MainActivity extends Activity {
    protected SurfaceView surface;

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

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

表面视图

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);
                }
            }
        }
    }
}
4

2 回答 2

1

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

于 2013-07-29T21:49:36.627 回答
0

您可以使用 traceview 查找滞留的位置。

查看带有 traceview介绍的分析。

干杯!

于 2013-07-27T21:26:15.203 回答