首页 > 解决方案 > 安卓工作室。线程休眠后应用程序崩溃

问题描述

我希望能够在 3 秒后更改文本视图的设置文本。为此,我创建了一个 try catch 语句,并告诉线程在执行下面的代码之前休眠 3000 毫秒。不幸的是,当我运行该应用程序时,程序只是等待 3 秒然后崩溃。任何帮助将不胜感激。

    Runnable runnable3 = new Runnable() {

        @Override
        public void run() {
            TextView sup_txt3 = findViewById(R.id.sup_txt3);
            sup_txt3.setText("Ooooohhhh this is very hard. I am receiving many thoughts");


            try{
Thread.sleep(3000);
            }catch(Exception e){

            }
            sup_txt3.setText("I am sensing the letter A");

        }
    };

标签: androidmultithreadingcrashtry-catchsleep

解决方案


我将 postDelayed() 用于此类任务

sup_txt3.postDelayed(() -> sup_txt3.setText("I am sensing the letter A", 3000);

我把它做短了,完整的代码是

sup_txt3.postDelayed(new Runnable() {
   @Override
   public void run() {
      sup_txt3.setText("I am sensing the letter A");
   }
}, 3000);

推荐阅读