我如何每隔16毫秒使()一个android.view.View无效?

时间:2017-08-29 22:56:52

标签: android multithreading frames

我知道有很多像这样的问题,但有一个答案对我没有用!

编辑1:我想编写一个“Pong”游戏。一种方法应该每帧重新计算并重绘球。

基本上我正在寻找另一种方法来执行此操作(每16毫秒更新一次视图以启动游戏):

Thread t = new Thread(){
    while (true){
        try{
            Thread.sleep(16);
        } catch (InterruptedException e) {

        }
        invalidate();
    }
}
t.start(); //here the code crashes

我已经通过HandlerTimerTasklink)和Runnable列出了一些内容。

我最好的尝试是当我得到android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views以下内容时:

Timer timer = new Timer();
final GameView v = this;
final TimerTask task = new TimerTask() {
    @Override
    public void run() {
        v.invalidate();
    }
};
timer.schedule(task, 100, 200);

编辑2:m0skit0的最佳方式:

Timer timer = new Timer();
final GameView v = this;
final TimerTask task = new TimerTask() {
    @Override
    public void run() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!pause)
                    v.update(); //my invalidate()-method
            }
        });
    }
};
timer.schedule(task, 0, 16);

对每个有工作想法的人:提前谢谢你!

1 个答案:

答案 0 :(得分:0)

Suggestion 1:
use View.postInvalidate() instead of View.invalidate().
here is postInvalidate() description:

public void postInvalidate ()

Cause an invalidate to happen on a subsequent cycle through the event loop. Use this to invalidate the View from a non-UI thread.

This method can be invoked from outside of the UI thread only when this View is attached to a window.

Suggestion 2:
use LIBGDX for games