condition signal from handler postDelayed?

1.1k Views Asked by At

I'm very new to Android programming so pls excuse my ignorance...

I'm trying to do simple Android app:

  • User presses a button, starts postDelayed job and then waits on conditional var
  • after timeout the postDelayer job should signal

    private final static long TIMEOUT = 10000;
    private Handler mHandler;
    final Lock lock = new ReentrantLock();
    final Condition condition  = lock.newCondition();
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mHandler = new Handler();
        ...
    }
    
    private void timeOutSignal() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
    
                Log.d(">> ", "---> timeout notify");
                lock.lock();
                try {
                    condition.signal(); // releases lock and waits until doSomethingElse is called
                } finally {
                    lock.unlock();
                }
            }
        }, TIMEOUT);
    }
    public void buttonClick(View view) {
    
        timeOutSignal();
        Log.i("???", "... WAIT");
    
        lock.lock();
        try {
            condition.await();
        } catch (InterruptedException e) {
            // todo
        } finally {
            lock.unlock();
        }
    
        Log.i("???", "... WAIT DONE !");
    }
    

What happens is that buttonClick() is stuck waiting and I'm not even seeing the "---> timeout notify" message after timeout...

What I'm doing wrong ?

EDIT: Tried to fix messed up example...

1

There are 1 best solutions below

1
On BEST ANSWER

You can't do what you're trying to do. Handlers run on Looper threads. Handlers that are created with the default constructor will use Looper thread that it is currently running in. In this case, it is the main Looper thread (or UI thread). So, you're locking on the UI Thread and the Handler unlocks on the UI Thread, but it will never reach that point because you're blocking the UI Thread.

Also, at no point do I see you actually calling the method that posts to the Handler.