Android线程停止

时间:2017-06-26 18:17:00

标签: android multithreading

我正在测试创建游戏循环而不使用表面视图,但我无法让线程连续运行。在下面的代码中,我希望文本视图能够连续显示递减数字,但它只显示一次。

public class ActivityGameTest extends AppCompatActivity {
int bigNumber = Integer.MAX_VALUE;
Thread gameThread;
TextView myText;
private Handler uiHandler;
boolean mRun;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_test);
    myText = (TextView) findViewById(R.id.txtHello);
    uiHandler = new Handler();

    gameThread = new Thread(null, processFrame, "ProcessFrame");
    mRun = true;
    gameThread.start();
}

private Runnable processFrame = new Runnable() {

    @Override
    public void run() {
        while (mRun) {
            updateFrame();

//编辑 - 添加这些行

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


        }
    }
};

private void updateFrame() {
    bigNumber--;
    uiHandler.post(showFrame);
}

private Runnable showFrame = new Runnable() {
    @Override
    public void run() {
        myText.setText(Integer.toString(bigNumber));
    }
};

}

1 个答案:

答案 0 :(得分:0)

UI的更新应该在android的UI线程上运行... 正如here所指出的那样,你可以在一个函数中包含对android ui线程的调用,并在需要时调用它。