安卓中四种实现延时操作方法

1.使用Handler

class MainActivity : AppCompatActivity() {
    private var handler = Handler(Looper.getMainLooper())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        handler.postDelayed({
            Toast.makeText(this, "hello", Toast.LENGTH_LONG).show()
        }, 3000)
    }
}

2.使用Activity里面的view

下面的textView是当前activity对应的布局文件的一个View

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView.postDelayed({
            Toast.makeText(this, "hello", Toast.LENGTH_LONG).show()
        }, 3000)
    }
}

3.使用Thread

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Thread(Runnable {
            Thread.sleep(3000)
            runOnUiThread {
                Toast.makeText(this, "hello", Toast.LENGTH_LONG).show()
            }
        }).start()
    }
}

4.使用协程

  1. 引入协程
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1"
  1. 实际使用
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        GlobalScope.launch(Dispatchers.Main) {
            delay(3000)
            Toast.makeText(this@MainActivity, "hello", Toast.LENGTH_LONG).show()
        }
    }
}

你可能感兴趣的:(安卓中四种实现延时操作方法)