-
-
Save Struka9/6fdb8b96211544ed64a35cc052f2c5af to your computer and use it in GitHub Desktop.
This file contains 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
// MyBoundService.kt | |
class MyBoundService: Service() { | |
// Extend the Binder class and expose the service instance through a method | |
inner class MyServiceBinder: Binder() { | |
fun getService() = this@MyBoundService | |
} | |
private val myBinder = MyServiceBinder() | |
fun doWork() { | |
// ... | |
} | |
override fun onBind(intent: Intent?): IBinder { | |
// Support binding to this service | |
return myBinder | |
} | |
} | |
// MyActivity.kt | |
class MyActivity: AppCompatActivity { | |
private val serviceConnection = object: ServiceConnection { | |
override fun onServiceConnected(name: ComponentName?, binder: IBinder) { | |
val myServiceBinder = binder as MyServiceBinder | |
service = myServiceBinder.getService() | |
} | |
override fun onServiceDisconnected(name: ComponentName?) { | |
service = null | |
} | |
} | |
// ... | |
private var service: MyBoundService? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.my_activity) | |
// ... | |
doWorkBt.setOnClickListener { | |
service?.doWork() | |
} | |
// ... | |
} | |
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