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

Why did the great "BT download" technology fail?

Last April, Bob Delamar and Jeremy Johnson became ...

How do brands develop and create marketing IP?

If a mature brand still has no representative mar...

Li Yu uses words to tell you how exciting life with ups and downs is!

This article was first published by Hunzhi Educat...

What are the operating routines of B-side products?

It is widely circulated both among the public and...

Summer hibernation, winter hibernation...are there such lazy fish?

Here’s some fun fact for you: All vertebrates sle...

Besides VR, what else can leverage the Internet of Things in 2016?

In 2016, the Internet of Things was written into ...

How does Tongcheng operate blind boxes that are popular all over the Internet?

Tongcheng Travel spent only 9 yuan to buy the rea...