java - 了解 UI 线程

标签 java android android-handler ui-thread android-looper

例如,有很多任务发布到UI线程如下。

Handler handler = new Handler(Looper.getMainLooper());

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Some logic to display/update something in UI
    }
}, 5000);

当 android 应用程序进入后台时,这些任务会发生什么情况?

这些任务会在后台处理吗?整个UI线程会不会在后台挂起?或者?发布到 UI 线程的所有任务都已暂停?

当 Activity 完全加载后没有任务发布到 UI 线程时会发生什么?如果Looper中没有任务,它会被挂起吗?

提前致谢。

最佳答案

让我们先了解几个术语。

Handler :

A Handler allows communicating back with UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. In technical terms, it is a way to post Messages or runnable to your associated thread message queue.

所以处理程序总共执行了两个任务

  • 安排消息和可运行对象在未来的某个时间点执行;和
  • 将要在不同于您自己的线程上执行的操作加入队列。

那么如何安排一个

post(Runnable),
postAtTime(Runnable, long),
postDelayed(Runnable, Object, long),
sendEmptyMessage(int),
sendMessage(Message), 
sendMessageAtTime(Message, long),
sendMessageDelayed(Message, long).

Looper:

Whatever I mentioned earlier is supported by Looper It has a loop() method which keeps running and listening for the new messages, main thread has one running all the time so you can receive messages from another thread to this thread, if you are creating your own thread and want to listen then don't forget to call prepare() in the thread that is to run the loop.

一个简单的例子

     class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

现在回答你的问题:

1: Things(Threads and so Looper and Handler) 一直运行直到它被用户完成或被系统杀死。

2: Looper 有一个 loop() 方法,它会处理队列中的每条消息,并在队列为空时阻塞。

3:如果从后台线程更新 UI,请确保应用程序在前台或在 onDestroy() 中终止后台线程,您可以使用 handler.getLooper().quitSafely() 退出循环处理消息handler.looper.quit() 如果处理程序附加到主线程。

建议在方向更改或其他配置更改的情况下确保终止后台线程。

关于java - 了解 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081193/

相关文章:

Java - ResultSet 更改数据库列名称以在 JTable 中显示

java - 如果我的运行类是 junit,如何初始化 guice?

android - 如何将 View 转换为Drawable

android - adb pull -> 未找到设备

android - 指定的消息队列同步屏障 token 尚未发布

java - 如何在 Android 中设置带有特定步骤的进度条?

android - 在主线程上创建的 Android View 、 Activity/窗口和处理程序是否有单独的消息队列?

java - 当 session 超时导致多部分表单 POST 中断时出现异常

java - Spring 启动: Cannot access page html on localhost (404)

java - 如何让我的广告横幅出现在我的应用程序上而不带走整个应用程序?