2018/12/02

Communication between a working thread and UI thread

Some API like requesting user location, needs to be called in the main UI thread. How to send a message from a working thread to main UI thread? Here is an example:

class T4StationService : Service() {
var mLocSer: LocationService? = null
var mHandler: MyHandler? = null
inner class MyHandler(looper: Looper) : Handler(looper) {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
// call some function that needs to be called in UI thread
}
}
override fun onCreate() {
super.onCreate()
// create handler in the main UI thread
mHandler = MyHandler(Looper.getMainLooper())
// start a new thread
Thread(MyRunnable()).start()
}
// inner is required to access outter class method
inner class MyRunnable : Runnable {
override fun run() {
// send message to handle running in UI thread
val message = mHandler?.obtainMessage(1)
message?.sendToTarget()
(0..15).map {
println("about to sleep")
Thread.sleep(1000)
}
}
}
}

Post Code on Blogger

Simplest way to post code to blogger for me: <pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black;overflow-x:...