使用静态处理程序更新 UI 线程

Using a Static Handler to update the UI thread

当使用后台线程工作时,通常您会通过处理程序更新 UI。

实现此目的的一种方法是在 class 级别定义处理程序,如 this answer, and this answer

中所述
final Handler handler = new Handler(){
  @Override
  public void handleMessage(Message msg) {
    //update UI or call class methods here
  }
};

但是,此构造将导致以下警告

Handler class should be static otherwise memory leaks might occur

另一种方法是使用静态内部 class,如 this answer, and this answer

中所述
static class MyHandler extends Handler {
    private final WeakReference<Type> myWeakReference; 

    MyHandler(Type reference) {
        myWeakReference = new WeakReference<Type>(reference);
    }
    @Override
    public void handleMessage(Message msg)
    {
       //Update UI or call class methods here using weak reference
    }
}

但是,根据 Android 文档,这种形式的构造函数已被弃用。

public处理程序()

This constructor is deprecated. Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, {link android.view.View#getHandler}, or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers.

当前应该如何从 Handler 更新 UI,Handler 是否仍应用于此目的。

正如您在文档中所述,它说要使用 Looper.getMainLooper(),只需将您的代码更改为:

MyHandler(Type reference) {
    super(Looper.getMainLooper());
    myWeakReference = new WeakReference<Type>(reference);
}

从 main/UI 线程更新 UI。