Several methods to implement delayed operation in Android development

Several methods to implement delayed operation in Android development

Using Handler and Runnable

The Handler class can send and process thread-related messages and Runnable objects. The postDelayed method can delay the execution of a Runnable object for a period of time.

 Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { // 延迟后要执行的操作} }; handler.postDelayed(runnable, 1000); // 延迟1000毫秒执行

Using Thread and sleep

You can use the sleep method in a new thread to achieve the delay effect. Be careful not to use this method in the UI thread, otherwise it will cause the interface to freeze.

 new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); // 延迟2000毫秒// 延迟后要执行的操作,不要进行UI操作,如果需要使用Handler } catch (InterruptedException e) { e.printStackTrace(); } } }).start();

If you need to perform operations in the UI thread, you can use a Handler to send the results back to the main thread.

Using Timer and TimerTask

The Timer class can schedule one-time or recurring tasks to execute after a specified delay.

 Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // 延迟后要执行的操作// 如果需要更新UI,使用Handler将结果发送回主线程} }, 1000); // 延迟1000毫秒执行

Timer is not designed for concurrency and does not provide thread safety for multiple tasks.

Using ScheduledExecutorService

ScheduledExecutorService is an interface in the Java concurrency package that is used to execute commands after a given delay or periodically.

 ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.schedule(new Runnable() { @Override public void run() { // 延迟后要执行的操作} }, 1, TimeUnit.SECONDS); // 延迟1秒后执行

Use ObjectAnimator or ValueAnimator (animation related)

If you are working with an animation and want to perform some action after the animation ends, you can use the listeners of the Animator class to achieve an effect similar to a delay.

 ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f); animator.setDuration(1000); // 设置动画时长为1000毫秒animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); // 动画结束后要执行的操作} }); animator.start();

Although this method is related to animation, it is also a method for performing an action after a certain amount of time.

Using RxJava and Kotlin Flow

RxJava provides a timer operator to delay the entire operation.

 Observable.timer(3, TimeUnit.SECONDS) .observeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( result -> { // 处理结果延迟后执行的操作}, throwable -> { // 处理错误} );

If you use Kotlin and have introduced coroutine support, you can use the delay function to implement delays.

 GlobalScope.launch(Dispatchers.Main) { delay(3000) // 延迟3000毫秒// 延迟后执行的操作}

In practical applications, you should avoid starting coroutines in GlobalScope and start them in appropriate lifecycle scopes (such as ViewModel's scope).

<<:  The launcher process starts and the user interface is presented, revealing the key steps of each stage

>>:  Android animation framework, making panning animation more attractive

Recommend

How should operations perform user segmentation? 8 steps to clear your mind

If the thinking section gives us the angle to thi...

Perhaps this is the "ultimate secret" of user operation

Among all operations , user operation is the most...

How Facebook reduces FOOMs in its app

At Facebook, we're committed to making apps s...

I didn't expect you to be such a tiger!

Today (January 26) is the 24th day of the twelfth...

Build offline event promotion skills from 0-1!

There are activities every day, but good activiti...

Why don't electric cars use nuclear batteries?

So far, the greatest energy that humans can maste...

Artemis Project: Humans will return to the moon and build permanent settlements

Author | Feng Ziyang Audit | Huang Jian Editor | ...

Tips for rapid website inclusion, how to increase website inclusion volume?

For website optimizers, there are several points ...