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

Counterpoint: U.S. electric vehicle sales increased 52% year-on-year in Q3 2022

Despite macroeconomic headwinds, U.S. electric ve...

Xiaohongshu Hot Note Titles (Tutorial Included)

There are too few eyes in the notes and the numbe...

AI has helped reduce in-flight food waste by 63%. How did it do that?

How AI can help airlines reduce food waste on boa...

When bees move to cities, can humans be good neighbors?

When it comes to bees, do you first think of beeh...

Apple removes paid copycat version of "Travel Frog", you may have a fake "son"

Recently, according to Techweb, Apple App Store h...

Advertising: 8 creative writing tips to increase your click-through rate!

We all know that the role of creativity is to att...

What is the difference between server hosting and virtual hosting?

The advantages of server hosting are that users h...

Do you know about the top 10 most popular fission marketing?

The article breaks down the top ten most popular ...