【问题标题】:How to delay "runOnUiThread" in android?如何在android中延迟“runOnUiThread”?
【发布时间】:2020-06-22 09:23:48
【问题描述】:

我已经实现了一种向服务器发送数据的方法,但我想将实现的功能失败消息延迟大约 20 毫秒,

我的代码是

public void onFailure(Call call, IOException e) {
              
                call.cancel();
                Log.d("FAIL", e.getMessage());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        responseText.setText("Failed to Connect to Server. Please Try Again.");
                    }
                });
            }

【问题讨论】:

  • 这能回答你的问题吗? How to call a method after a delay in Android
  • 它在 runOnUiThred 上不起作用
  • 延迟 UI 线程是你不应该做的事情。将失败方法放在单独的线程中,如 ASyncTask 或使用 Handler 或类似的并在那里延迟。
  • @AHoneyBustard 但没有人在这里延迟 UI 线程,这里的情况更多是关于延迟一个动作并在一段时间后执行它而不是冻结 UI 线程:)
  • @Mariusz Brona 我知道,但这个问题可以很容易地解释为其他...

标签: android


【解决方案1】:

你可以用这个:

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        TextView responseText = findViewById(R.id.responseText);
        responseText.setText("Failed to Connect to Server. Please Try Again.");
    }
}, 20)

new Handler(Looper.getMainLooper())runOnUiThread {} 的作用基本相同,但执行方式略有不同。对于您的用例,第一个选项非常适合,因为它允许延迟。您可以在这里找到更多解释:

runOnUiThread vs Looper.getMainLooper().post in Android

【讨论】:

  • 您是复制粘贴还是将其更改为 Runnable?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2023-03-13
相关资源
最近更新 更多