Since new coroutines feature became available in Kotlin version 1.1 you can use non-blockingdelay function with such signature:
suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS)
In Kotlin 1.2 it is still located in kotlinx.coroutines.experimental package. Experimental status of coroutines is described here.
UPD: Kotlin 1.3 was released, coroutines were moved to kotlinx.coroutines package, they are no longer experimental feature.
UPD 2: To use this method inside non-suspendable methods it's possible to make it blocking, like any other suspendable methods, by surrounding with runBlocking {}:
Another response suggests Thread.sleep(millis: Long). Personally I prefer the TimeUnit class (since Java 1.5) which provides a more comprehensive syntax.
They use Thread.sleep behind the scene, and they can throw InterruptedException too. Unfortunately, as pointed by @AndroidDev in a comment, they do not cooperate with Kotlin coroutines (since Kotlin 1.1). So we should prefer delay function in this context.
public suspend fun delay(timeMillis: Long): Unit
public suspend fun delay(duration: Duration): Unit
You can achieve this easily with Kotlin coroutines
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
CoroutineScope(Dispatchers.IO).launch {
delay(TimeUnit.SECONDS.toMillis(3))
withContext(Dispatchers.Main) {
Log.i("TAG", "this will be called after 3 seconds")
finish()
}
}
Log.i("TAG", "this will be called immediately")
}
}