Created
January 24, 2019 18:26
-
-
Save aanandshekharroy/a1576ec62bd99ad3780118dd80a68f08 to your computer and use it in GitHub Desktop.
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
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