Kotlin:如何在不卡住 UI 的情况下延迟 Android 中的代码

标签 kotlin ui-thread background-thread

我正在尝试延迟我尝试过的 Kotlin 中的代码

Thread.sleep(1000)

但它卡住了用户界面。

有人知道为什么会这样吗
以及如何在不卡住 UI 的情况下进行延迟?

最佳答案

出了什么问题

用法 Thread.sleep(...)

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.



对于 OP(原始海报/提问者)的澄清:

It freezes the UI, does somebody know why this is happening?



正如上面 Java 官方文档中提到的,您在 UI 中遇到了某种卡住,因为您在主线程中调用了它。

主线程,或者如果你在 Android 中做你的事情,它通常被称为 UI 线程:

On the Android platform, applications operate, by default, on one thread. This thread is called the UI thread. It is often called that because this single thread displays the user interface and listens for events that occur when the user interacts with the app.



如果不使用多线程 API 的帮助(例如 RunnableCoroutinesRxJava ),您将自动调用 Thread.sleep(1000)在 UI 线程上,这就是您遇到这种情况的原因 “用户界面卡住”经验因为,其他UI Operations被阻止访问线程,因为您已对其调用暂停。

And how to delay without freezing the ui?



利用可用 API 的强大功能进行多线程处理,到目前为止,最好从以下选项开始:

1. 可运行

在 Java 中

// Import
import android.os.Handler;

// Use
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
     // do something after 1000ms
  }
}, 1000);

在 Kotlin
// Import
import android.os.Handler;

// Use
val handler = Handler()
handler.postDelayed({
     // do something after 1000ms
}, 1000)

2. Kotlin 协程
// Import
import java.util.*
import kotlin.concurrent.schedule

// Use
Timer().schedule(1000){
    // do something after 1 second
}

3. RxJava
// Import
import io.reactivex.Completable
import java.util.concurrent.TimeUnit

// Use
Completable
     .timer(1, TimeUnit.SECONDS)
     .subscribeOn(Schedulers.io()) // where the work should be done
     .observeOn(AndroidSchedulers.mainThread()) // where the data stream should be delivered
     .subscribe({
          // do something after 1 second
     }, {
          // do something on error
     })

在这三者中,目前,RxJava 是在应用程序中实现多线程和处理大量数据流的方式。但是,如果您刚刚开始,最好先尝试基础知识。

引用文献
  • https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
  • https://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
  • https://github.com/ReactiveX/RxJava
  • https://github.com/Kotlin/kotlinx.coroutines
  • 关于Kotlin:如何在不卡住 UI 的情况下延迟 Android 中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348728/

    相关文章:

    后台线程中的android addView

    android - 得到 ArithmeticException : divide by zero, 但我没有在任何地方除以零

    android - Realm Kotlin 迁移 Android String

    java - 如何获取 Gradle 中生命周期库的版本?

    c# - 在c#中使用async和await时UI将被阻塞

    Android - uiThread block 如何执行?

    android - v24 AsyncLayoutInflater 在 ui 线程上膨胀

    kotlin - kotlin中如何使用子类调用父静态方法?

    python - App Engine 上后台线程的日志在哪里?

    ios - 为什么我的应用程序在我将数据上传到 Firebase 时卡住?