How can I have something like this java code in Kotlin? Even the IDE does not convert it to Kotlin perfectly!
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
I tried using inner class
but then I was not able to use it like this:
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
You're creating an anonymous class here. In Kotlin, these are object expressions :
val connection = object: ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
//Something to do
}
override fun onServiceDisconnected(arg0: ComponentName) {
//Something to do
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.