srv242 srv242 - 2 months ago 15
Android Question

Handler from a non-Activity class

Can we execute

handler.postDelayed(runnable,400)


from a non-
Activity
class?

I have a controller class, assume it as an adapter. Can we use
Handler
there?

I tried by debugging my app using break points, but the control is not reaching

handler.postDelayed(runnable,400)


Can anyone help me regarding this?

Actually I'm using OCR. If certain match is made, I want to return automatically to my main activity. I suppose its a looper. I need to capture the photograph of it also. For that I need to use a handler.

Answer

Can we execute handler.postDelayed(runnable, 400) from a non-Activity class?

Yes, you can.

Any Handler is associated with a Thread (not an Activity or another object) and the Thread's message queue. Handlers post/process Messages and Runnables to/from the queue that is handled by Looper.

When you create a Handler within the main thread (e.g. in Activity class) you post/send messages and Runnables (with post(), postDelayed(), sendMessage() etc) to the running loop. However, by default, threads don't have the loop running unless you create one with the call to Looper.prepare() first and Looper.loop() afterwards.

In case a Handler created on a background thread is to post messages and Runnables to the main's thread queue either

  • pass the main thread's Looper to the Handler's constructor
  • or use new Handler(Looper.getMainLooper()).

I tried debugging my app using break points, but the control is not reaching.

I assume either your code logic never reaches "the control" or the handler is created within a background thread without preparing and looping Looper so that the runnable can't be processed by the handler.