Skip to content

Instantly share code, notes, and snippets.

@Struka9
Created August 13, 2019 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Struka9/6d0686c3dac34e636b2aa71cd77a372d to your computer and use it in GitHub Desktop.
Save Struka9/6d0686c3dac34e636b2aa71cd77a372d to your computer and use it in GitHub Desktop.
// 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