ryannmahajan
ryannmahajan

Reputation: 33

When is a Handler associated to a looper?

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.

  1. How does it identify what the current thread is, though?
  2. Why is calling new Handler() in specific methods (onLooperPrepared(), onCreate() ) mandatory?

Upvotes: 1

Views: 146

Answers (2)

Vladyslav Matviienko
Vladyslav Matviienko

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

Robbit
Robbit

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 :

enter image description here

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

Related Questions