android try/catch 执行序列

android try/catch execute sequence

我想要实现的是点击后,应用程序显示 toasts 消息 "TEXT1",并一直显示 TEXT1,直到随机完成其他函数调用 20 次 interval/delay。调用函数后,显示 toast 消息 "TEXT2"。我的问题:TEXT1 在应用程序完成函数调用之前不会显示。并且 TEXT1 跟上执行 20 次函数调用所花费的时间,然后 TEXT2 显示 up.My 代码:

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.example:
                Toast.makeText(getBaseContext(),"Please wait until finish",Toast.LENGTH_SHORT).show();
                int i = 0;
                while (i <= 19 ){

                    int delay = new Random().nextInt(5000);
                    try {
                            Thread.sleep(delay);
                        } catch(InterruptedException ex) {
                            Thread.currentThread().interrupt();
                        }
                    //some function here
                    i++;
                }
                Toast.makeText(getBaseContext(),"Finished",Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

永远不要阻塞 UI 线程!

所有用户界面操作都在 UI 线程中处理。如果您使用 Thread.sleep 调用阻塞 UI 线程,则会发生 ANR(应用程序无响应)。此外,Thread.sleep 永远不是创建计时器的正确方法,除非您正在编写工作线程的核心心跳。

相反,您应该使用 Handler.postDelayed:

public void onClick(View v) {
    final Handler handler = new Handler();
    final Random random = new Random();

    Runnable runnable = new Runnable() {
        private int count = 0;

        @Override
        public void run() {
            count++;
            if(count > 20) { // 20 times passed
                Toast.makeText(getBaseContext(), "Finished", LENGTH_SHORT).show();
                return;
            }

            Toast.makeText(getBaseContext(), "Please wait until finish", LENGTH_SHORT).show();
            handler.postDelayed(this, random.nextInt(5000));
        }
    };
    runnable.run();
}

编辑:OP 想使用这样的东西。 https://gist.github.com/SOF3/07c3c110aa214fcdd752e95573b7076f

另请参阅:

  • Android - running a method periodically using postDelayed() call
  • How to call a method after a delay in Android
  • Waiting in android app