1. started-service
- Asynctask is deprecated!
- works on main thread
use this instead of asynctask on Java
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(() -> { // doInBackground
//Background work here
handler.post(() -> { // onPostExecute
//UI Thread work here
});
});
or with kotlin coroutines
GlobalScope.launch {
coroutineScope {
// onPreExecute
launch {
// doInBackground
delay(5000)
}
}
}
// also
GlobalScope.launch(Dispatchers.IO) {
// doInBackground
val answer = doNetworkCall()
withContext(Dispatchers.Main){
// main
tvTitle.text = answer
}
}
or with runOnUIThread()
Thread{
// background
runOnUiThread {
// main
}
}.start()
or with post()
method
Thread{
// background
someView.post {
// main
}
}.start()
or with handler
Thread{
// background
Handler(Looper.getMainLooper()).post {
// main thread
}
}.start()
or with handleMessage()
handler = object : Handler(Looper.getMainLooper()){
override fun handleMessage(msg: Message) {
checkBox.isChecked = (msg.data.getInt("sleep_time", 0) > 3)
}
}
...
Thread{
val message = Message.obtain()
message.data = Bundle().apply {
putInt("sleep_time", 5)
}
handler.sendMessage(message)
}.start()
2. intent-service (Deprecated!)
- sub-class of started-service
- has own worker thread (asynctask)
- need to override
onHandleIntent()
- handles multi-threading details internally, creates a work queue for handle all intents
- automatically stops itself when work is complete (No need to use
stopSelf()
orstopService()
) - running style:
onStartCommand()
->work queue
->onHandleIntent()
started-service vs intent-service
-
started-service
- operates in main thread
- may block the ui
- used for short duration
-
intent-service
- operates in worker thread
- does not block the ui
- used for long process
3. bound-service
A bound service is the server in a client-server interface.
- returns data
- need to override
bindService()
- works on main thread
- for long-standing connection
onBind()
returnsIBinder
- If the calling component is destroyed then Bound Services too gets destroyed
- usage
- Generally
bindService()
inonStart()
andunBindService()
inonStop()
- If you want your Activity to bind to the service even when it is not visible,
bindService()
inonCreate()
andunBindService()
inonDestroy()
- Generally