34 lines
1.4 KiB
Kotlin
34 lines
1.4 KiB
Kotlin
package android.os
|
|
class Looper { companion object {
|
|
val owner=Thread.currentThread();private val main=Looper();private val other=Looper()
|
|
fun getMainLooper()=main
|
|
fun myLooper()=if(Thread.currentThread()===owner) main else other
|
|
} }
|
|
object SystemClock { fun elapsedRealtime()=CameraClock.now }
|
|
class Handler(val looper: Looper=Looper.getMainLooper()) {
|
|
fun post(r: Runnable): Boolean=postDelayed(r,0)
|
|
fun postDelayed(r: Runnable,ms: Long): Boolean {CameraClock.add(this,r,ms);return true}
|
|
fun removeCallbacks(r: Runnable) {CameraClock.remove(this,r)}
|
|
}
|
|
object CameraClock {
|
|
@Volatile var now=0L
|
|
private data class Task(val h: Handler,val r: Runnable,val due: Long,val order: Long)
|
|
private val tasks=java.util.PriorityQueue<Task>(compareBy<Task> {it.due}.thenBy {it.order})
|
|
private var serial=0L
|
|
@Synchronized fun add(h: Handler,r: Runnable,ms: Long) {tasks.add(Task(h,r,now+ms,serial++))}
|
|
@Synchronized fun remove(h: Handler,r: Runnable) {tasks.removeIf {it.h===h && it.r===r}}
|
|
@Synchronized fun reset() {tasks.clear();now=0;serial=0}
|
|
fun advance(ms: Long=0) {
|
|
val end=now+ms
|
|
while(true) {
|
|
val task=synchronized(this) {if(tasks.peek()?.due?.let {it<=end}==true) tasks.poll() else null} ?: break
|
|
now=task.due;task.r.run()
|
|
};now=end
|
|
}
|
|
fun await(condition: ()->Boolean) {
|
|
val deadline=System.nanoTime()+3_000_000_000
|
|
while(!condition()) {advance();check(System.nanoTime()<deadline);Thread.sleep(1)}
|
|
advance()
|
|
}
|
|
}
|