new Handler() 和 new Handler(Looper.myLooper()) 的区别

Difference between new Handler() and new Handler(Looper.myLooper())

我查看了官方文档,但我似乎无法找到 new Handler()new Handler(Looper.myLooper())

之间是否有任何区别

new Handler()

Default constructor associates this handler with the Looper for the current thread.

Looper myLooper ()

Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.

Handler Source code开始,如果你不提供looper,它会默认在Handler所在的当前循环器上运行已初始化,即 Looper.myLooper().

所以

new Handler()

new Handler(Looper.myLooper())

基本相同

但是 Handler(Looper looper) 构造函数可用于您想要更改线程而不是创建句柄对象的线程的情况。

例如,如果您在后台线程中并想 运行 在主线程中执行某些操作,您将不能简单地使用 new Handler() 来完成,因为该处理程序将在同一个线程。

在这里你可以使用带有 Looper 参数的构造函数,例如:

new Handler(context.getMainLooper())

Handler(Looper.getMainLooper()) //if you don't have context

处理程序() 现在不推荐使用此构造函数。

因此,我们需要使用:

  Handler(Handler.Callback callback)   OR

  Handler(Looper looper)               OR

  Handler(Looper looper, Handler.Callback callback)

为了在 android 中创建 Handler 实例。

有关详细信息,您可以查看此 link: https://developer.android.com/reference/android/os/Handler