Ehsan Nokandi
Ehsan Nokandi

Reputation: 1973

unresolved refrence: @MusicService

I have used this class inside my service class, to help me access the service from my activity. My service class name is MusicService.

class MusicBinder: Binder(){
      fun getService():MusicService{
          return this@MusicService
      }
}

But i get this error:

unresolved reference: @MusicService

I tried 'inner' keyword for MusicBinder class but it didn't work. I would appreciate if you helped me with this.

Update: here is a part of my activity that i use to access service.

private val serviceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {
        }
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {1
            musicService = p1.getService()
        }
    }

Upvotes: 0

Views: 429

Answers (1)

3mpty
3mpty

Reputation: 1385

Proper Android Service binding implementation in Kotlin:

class MusicService : Service() {

    private val musicBinder = MusicBinder()

    inner class MusicBinder: Binder() {
        fun getService() : MusicService {
            return this@MusicService
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return musicBinder
    }
}

and in your Activity:

private var isBinded = false
private var musicService: MusicService? = null
private val musicServiceConnection = object: ServiceConnection {
    override fun onServiceDisconnected(name: ComponentName?) {
        musicService = null
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        musicService = (service as MusicService.MusicBinder).getService()
    }
}

fun bindService() {
    if (bindService(Intent(this, MusicService::class.java), musicServiceConnection, Context.BIND_AUTO_CREATE)) {
        isBinded = true
    } else {
        // log error here
    }
}

fun unbindService() {
    if (isBinded) {
        unbindService(musicServiceConnection)
        isBinded = false
    }
}

override fun onDestroy() {
    unbindService()
    super.onDestroy()
}

More info can be found here: https://developer.android.com/reference/android/app/Service.html or in Service class JavaDoc.

Upvotes: 1

Related Questions