咨询:new Handler()与new Handler(Looper.myLooper())是否存在差异?
Are
new Handler() and new Handler(Looper.myLooper()) functionally different? Short answer: In almost all practical scenarios, these two lines of code are completely equivalent — they end up associating the Handler with the same Looper from the current thread. Let me break down why:
- First, let's look at how the no-argument
Handlerconstructor works under the hood. Internally, it directly delegates to the constructor that takes aLooperparameter, passing in exactlyLooper.myLooper()as the argument. Sonew Handler()is just syntactic sugar fornew Handler(Looper.myLooper()). - As you noted,
Looper.myLooper()returns the Looper instance tied to the current thread, ornullif the thread hasn't initialized a Looper (e.g., a regular worker thread that never calledLooper.prepare()). In either case, both constructor calls will behave identically:- If there's a valid Looper for the current thread, both will create a Handler linked to that Looper's message queue.
- If there's no Looper (returns
null), both will throw aRuntimeExceptionwith a message like "Can't create handler inside thread that has not called Looper.prepare()".
The only real difference is readability: explicitly passing Looper.myLooper() makes your intent clearer for other developers reading the code, whereas the no-argument constructor is more concise. But functionally, they do exactly the same thing.
内容的提问来源于stack exchange,提问作者d3xter
相关产品推荐
相关产品推荐

