Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: delay function execution and possibility to cancel its execution

Tags:

java

android

I have a animated loader in my application right now.

    public void startLoader() {
        Runnable task = new Runnable() {
             @Override
             public void run() {
                lock = true;
                loader.setVisibility(View.VISIBLE);
            }
        };
        runOnUiThread(task);
    }

    public void stopLoader() {
        Runnable task = new Runnable() {
             @Override
             public void run() {
                lock = false;
                loader.setVisibility(View.GONE);
            }
        };
        runOnUiThread(task);
    }

Now I want it to work like this:

stopLoader should have an delayed execution of like 1000ms, so it dissapears 1 second after stopLoader is called. but if the startLoader is called within that 1000ms the stopLoader timer would be cancelled.

What is the best way to implement this?

like image 425
pouwelsjochem Avatar asked Jul 05 '14 13:07

pouwelsjochem


Video Answer


1 Answers

You should use Handler instead of runOnUiThread.
With handler you can cancel any delayed task using handler.removeCallbacks(runnable).

Handler mHandler = new Handler();
Runnable startTask = new Runnable() {
         @Override
         public void run() {
            lock = true;
            loader.setVisibility(View.VISIBLE);
        }
    };
Runnable stopTask = new Runnable() {
         @Override
         public void run() {
            lock = false;
            loader.setVisibility(View.GONE);
        }
    };
public void startLoader() {
   mHandler.removeCallbacks(stopTask);
   mHandler.post(startTask);
}

public void stopLoader() {
   mHandler.postDelayed(stopTask, 1000);
}

Read more here

like image 100
Yoavst Avatar answered Oct 17 '22 20:10

Yoavst