Android - The right way to wait for a handler object to be created

People,

Here is the simplified code for my background thread:

public class MyThread extends Thread { private Handler _handler; public void run() { Looper.prepare(); this._handler = new Handler(); Looper.loop(); } public void DoSomething() { if (!this.isAlive()) { this.start(); } this._handler.post(blah); } } 

The problem is that the background thread may not have created a handler object yet when calling post (). Essentially, I need a wait loop to initialize the handler object. What generates the accepted method of this in Android?

Thank you in advance for your help.

Regards, Peter

+6
source share
1 answer

You can set the flag after initializing the handler and wait for this flag before calling post .

An easy way to wait for a flag in a parallel system is CountDownLatch . It will start at 1 and decrease after the handler initializes. Check out the details here: http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/CountDownLatch.html

+3
source

Source: https://habr.com/ru/post/898720/


All Articles