Last active
June 1, 2019 20:16
-
-
Save christianb/015b8ec33a09f193bb3621f0d9c85ac1 to your computer and use it in GitHub Desktop.
How to create a Thread with an Looper, called by a Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Understanding Handler and Looper in Android | |
// by Rahul Rastogi | |
// https://medium.com/@rastogi.tech/understanding-handler-and-looper-in-android-c6fa673c6822 | |
var handler: Handler? = null | |
Thread { | |
Looper.prepare() // Creating a Looper for this thread. | |
// Creating a Handler for given Looper object. | |
handler = Handler(Looper.myLooper(), // get Looper for current Thread | |
Handler.Callback { msg -> | |
// Processing incoming messages for this Handler. | |
// Receiving extras from Message | |
val bundle: Bundle? = msg.data | |
Log.d("", "Handler:: Extras: ${bundle}") | |
Log.d("", "Handler:: Background Thread ID ${Thread.currentThread().id}") | |
// Looper.myLooper().quit() | |
return@Callback true | |
} | |
) | |
Looper.loop() | |
}.start() | |
Log.d("", "Handler:: UI Thread ID ${Thread.currentThread().id}") | |
// Posting a runnable to the handler | |
handler?.post { | |
// Thread's ID is of thread. | |
Log.d("", "Handler:: Background Thread ID ${Thread.currentThread().id}") | |
} | |
// Sending data using Message object. Handler's handleMessage(msg: Message?) method will receive this Message and perform appropriate action. | |
val extras = Bundle().apply { | |
putInt("PRICE", 100) | |
putString("PRODUCT_NAME", "Table Lamp") | |
} | |
val message = Message.obtain(handler).apply { | |
data = extras | |
} | |
handler?.sendMessage(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment