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

Windows 10's entry into the mobile field may pose a threat to Android?

Microsoft made several big announcements recently...

Tips for placing advertising on Tencent’s information flow!

As more and more industries move from the era of ...

Who are the people who choose to buy 4G mobile phones now?

Although 5G mobile phones are already very common...

IHS Markit: 5G Economic Report in the Post-COVID-19 Era

IHS Markit has released a new report, “The 5G Eco...

What is the magic of G219, China's most beautiful self-driving highway?

The Tibet section of National Highway 219 is a un...

How to obtain seed users during cold start?

In my previous company, I was involved in product...

Methods and strategies for creating hit events!

When user characteristics are strong, fine-graine...

To do Zhihu traffic promotion, you must master the skills!

There is no project that cannot be handled by tra...