Skip to content

Instantly share code, notes, and snippets.

@aanandshekharroy
Created January 24, 2019 18:26
Show Gist options
  • Save aanandshekharroy/a1576ec62bd99ad3780118dd80a68f08 to your computer and use it in GitHub Desktop.
Save aanandshekharroy/a1576ec62bd99ad3780118dd80a68f08 to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
var randomNumberGeneratorService: RandomNumberGeneratorService? = null
private lateinit var connection: ServiceConnection
var bounded = false
val TAG = MainActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
connection = object : ServiceConnection{
override fun onServiceDisconnected(componentName: ComponentName) {
Log.d(TAG,"Service disconnected.")
randomNumberGeneratorService = null
}
override fun onServiceConnected(componentName: ComponentName
, service: IBinder) {
Log.d(TAG, "Service connected.")
randomNumberGeneratorService = (service as RandomNumberGeneratorService.RandomNumberGeneratorServiceBinder).service
}
}
setupViews()
}
private fun setupViews() {
bind_service.setOnClickListener {
if(!bounded){
bindService(Intent(this, RandomNumberGeneratorService::class.java),connection,Context.BIND_AUTO_CREATE)
bounded = true
}
}
get_random_number.setOnClickListener {
if(!bounded){
generated_random_number.text = getString(R.string.service_not_bound)
}else{
generated_random_number.text = randomNumberGeneratorService?.randomNumber.toString()
}
}
unbind_service.setOnClickListener {
unbindSafely()
}
}
private fun unbindSafely() {
if (bounded) {
unbindService(connection)
bounded = false
}
}
override fun onDestroy() {
unbindSafely()
super.onDestroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment