How to execute scheduled tasks in the Android UI thread and androidui thread
In projects, we often encounter execution of scheduled tasks. For example, in the following scenario: Click the return key twice in two seconds, and the application exits. The general idea of implementing this function is as follows: Define a class variable goback and record the number of clicks. If you click it twice in 2 seconds, it will finish. If not, goback will be reset to 0, one of the implementation methods is as follows (1.0 ):
<span style="white-space:pre"></span>new Handler().postDelayed(new Runnable() {@Overridepublic void run() {goback = 0;}}, 2000);Next, I will discuss other methods to implement the above functions:
1.1 Use ScheduledExecutorService
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); Runnable task = new Runnable() { public void run() { /* Do something… */ } worker.schedule(task, 2, TimeUnit.SECONDS);
1.2 use Timer class
new Timer().schedule(new TimerTask() { @Override public void run() { // this code will be executed after 2 seconds }}, 2000);
1.3 still uses handler, but added message sending.
Handler myHandler = new DoSomething();Message m = new Message();m.obj = c;//passing a parameter heremyHandler.sendMessageDelayed(m, 1000);class DoSomething extends Handler { @Override public void handleMessage(Message msg) { MyObject o = (MyObject) msg.obj; //do something here } }
1.4 The last Thread class is a little cumbersome and is not recommended.
private static long SLEEP_TIME = 2 // for 2 second..MyLauncher launcher = new MyLauncher(); launcher.start();..private class MyLauncher extends Thread { @Override /** * Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any. */ public void run() { try { // Sleeping Thread.sleep(SLEEP_TIME * 1000); } catch (Exception e) { Log.e(TAG, e.getMessage()); } //do something you want to do //And your code will be executed after 2 second } }
There are almost five of the above practices, each of which has its own application scenarios. The code is relatively simple. You just need to use it directly.