【问题标题】:Android Studio. App crashes after thread sleeps安卓工作室。线程休眠后应用程序崩溃
【发布时间】:2020-11-12 23:08:44
【问题描述】:

我希望能够在 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");

        }
    };

【问题讨论】:

  • 检查logcat中的错误你可能试图从主线程外部更新用户界面
  • 除了@peprumo 所说的之外,您的try catch 并不是真的有用,是吗?您可能会捕获异常,这很酷,但您从不打印或查看它,它只是一个静默异常

标签: android multithreading crash try-catch sleep


【解决方案1】:

我将 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多