-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandlerThreadActivity.kt
More file actions
47 lines (39 loc) · 1.62 KB
/
HandlerThreadActivity.kt
File metadata and controls
47 lines (39 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class HandlerThreadActivity : AppCompatActivity() {
//work to do by requestHandler
val runnable = Runnable {
//some background job
responseHandler.sendMessage(Message()) //send message or post the job
responseHandler.post {
//some UI action
}
}
//handler on the main thread, override handleMessage if needed
val responseHandler = object: Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
//some action on UI
}
}
//handler on the background thread of handlerThread object
lateinit var requestHandler: Handler
//instead of Thread use reusable HandlerThread
//this can be also done by extend HandlerThread class and putting there Handler object
val handlerThread = HandlerThread("HandlerThread")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_handler_thread)
handlerThread.start() //start the thread
requestHandler = Handler(handlerThread.looper) //now Looper of handlerThread can be passed
button.setOnClickListener {
requestHandler.post(runnable) //post the job to MessageQueue
}
}
override fun onDestroy() {
super.onDestroy()
//remove tasks and messages from handlers
requestHandler.removeCallbacksAndMessages(null)
responseHandler.removeCallbacksAndMessages(null)
handlerThread.quitSafely() //quit HandlerThread's Looper
handlerThread.interrupt() //stop current job
}
}