Reputation: 105
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.
Upvotes: 2
Views: 1874
Reputation: 19949
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
Looper
to the Handler
's constructornew 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
.
Upvotes: 5
Reputation: 105
I used timer. It worked for me. LOL.
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Intent data = new Intent();
data.putExtra(OcrCaptureActivity.TextBlockObject, textBlock.getValue());
Log.d("Read Text : ", textBlock.getValue());
Base.base_activity.setResult(CommonStatusCodes.SUCCESS, data);
Base.base_activity.finish();
}
}, POST_DELAYED_TIME);
Upvotes: 0