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

Is alcohol a screen killer? Countless mobile phones have been killed!

Review expert: Zhu Guangsi, member of Beijing Sci...

Oracle: New TikTok board will have 4 Americans, possibly including Masayoshi Son

On Wednesday local time, Maria Bartiromo, anchor ...

How to improve user retention? 4 key points!

Before I start sharing knowledge points about ret...

Physical fitness for children and adolescents

Introduction to physical fitness resources for ch...

Douyin SEO ranking rules and operation procedures

In the first half of this year, ByteDance CEO Zha...

226 products and commonly used website operation tools recommended

I have compiled some tools and useful websites, h...

The ROI dilemma of B-side enterprise marketing!

China's Internet industry has been developing...