为什么Thread.sleep()不暂停我的代码?

时间:2019-09-23 20:52:17

标签: java android

基本上,我只是想尝试在Android Studio上练习,因此我正在制作一个flipcoin应用程序。

我希望一个圆形的进度条(最初是不可见的)变得可见两秒钟,然后又变得不可见。

使用我的代码,该代码在任何时候都不可见。

进度条的目的只是为了给大家一个悬念,然后我将宣布获胜者。

@Override
public void onCreate(Bundle savedInstanceState) {

    flipButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Random rd = new Random();
            int result = rd.nextInt(100) + 1;
            winner = result <= oddHeads? Winner.HEADS: Winner.TAILS;
            AnnounceWinner();
        }
    });
 }

private void AnnounceWinner() {
    progressBar.setVisibility(View.VISIBLE);
    i = progressBar.getProgress();
    pause(2000);
    progressBar.setVisibility(View.INVISIBLE);
}

private void pause(int delay) {
    try {
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

private void pause(int delay) {
    try {
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

问题::此代码将阻止UI线程(用于渲染UI,在这种情况下为渲染进度条)。这就是为什么看不到进度条的原因。

解决方案::在Android中,要安排可运行对象在将来的某个时间执行,您应该使用Handler API。

private static final long PAUSE_DURATION = 2000;
private boolean isAnnouncingWinner = false;

private final Handler handler = new Handler();
private final Runnable pauseRunnable = new Runnable() {
    @Override
    public void run() {
        // Write code after pausing
        isAnnouncingWinner = false;
        progressBar.setVisibility(View.INVISIBLE);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    flipButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Random rd = new Random();
            int result = rd.nextInt(100) + 1;
            winner = result <= oddHeads ? Winner.HEADS : Winner.TAILS;
            AnnounceWinner();
        }
    });
}

private void AnnounceWinner() {
    if (isAnnouncingWinner) {
        return;
    }

    isAnnouncingWinner = true;
    progressBar.setVisibility(View.VISIBLE);
    i = progressBar.getProgress();
    handler.postDelayed(pauseRunnable, PAUSE_DURATION);
}