Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// MyBoundService.kt
class MyBoundService: Service() {
val ACTION_DO_WORK = 0x2424
inner class MyHandler(looper: Looper): Handler(looper) {
override fun handleMessage(message: Message?) {
when(message?.what) {
ACTION_DO_WORK -> doWork()
}
}
}
private lateinit var messenger: Messenger
private lateinit var handler: MyHandler
override fun onCreate() {
super.onCreate()
// Create a background thread that eventually will be used to create the Messenger
val thread = HandlerThread("new-thread").apply {
start()
handler = MyServiceHandler(looper)
messenger = Messenger(handler)
}
}
fun doWork() {
// ...
}
override fun onBind(intent: Intent?): IBinder {
// Support binding to this service
return messenger.binder
}
}
// MyActivity.kt
class MyActivity: AppCompatActivity {
private val serviceConnection = object: ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder) {
service = Messenger(binder)
}
override fun onServiceDisconnected(name: ComponentName?) {
service = null
}
}
// ...
private var service: Messenger? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_activity)
// ...
doWorkBt.setOnClickListener {
messenger?.obtainMessage().also {
it.what = MyBoundService.ACTION_DO_WORK
messenger?.send(it)
}
}
// ...
}
override fun onStart() {
super.onStart()
val intent = Intent(this, MyBoundService::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
override fun onPause() {
super.onPause()
val intent = Intent(this, MyBoundService::class.java)
unbindService(intent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment