Reputation: 33
It seems like just calling new Handler() associates the handler with the current thread’s looper without any thread-specific arguments being passed to the constructor.
Upvotes: 1
Views: 146
Reputation: 10871
How does it identify what the current thread is, though?
By calling Thread.currentThread()
static method
Why is calling new Handler() in specific methods (onLooperPrepared(), onCreate() ) mandatory?
It actually is not mandatory depending on the task you want your handler to do.
But in general Looper is required for Handler to process messages.
More: How to Use Thread, Looper and Handler in Android
Upvotes: 0
Reputation: 4358
How does it identify what the current thread is, though?
If you dive into the calling new Handler()
, you'll see the source code, I'll show you :
The red rectangle shows you that you need a Looper
when you new Handler
.
The case mLooper==null
only occurs when you call new Handler
not in the UI thread, or you didn't call Looper.prepare()
in your work-thread.
Also, you can associate the handler with the current thread’s looper obviously, refer to Define a handler on the UI thread, like handler = new Handler(Looper.getMainLooper())
.
Upvotes: 1