Search code examples
androidandroid-servicekotlinandroid-service-binding

Creating unbound service in Kotlin


I'm trying to create a simple unbound service in kotlin, but I can't. When I override onBind() method in Java I can return null, but in kotlin it says I'm only allowed to return IBinder and not IBinder?, that means it can't be null. Any ideas how to fix that except rewriting MyService class into Java?

[SOLVED] Thank you, guys! I can realy change IBinder to IBinder?. It works!!


Solution

  • As Enrico mentioned you can change a type of IBinder to IBinder? and it will be still matching the interface.

    An example is below:

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

    In general, be careful when using Android Studio to override Android methods. The real problem comes when it generates non-null type when the system actually can return a null reference. It causes runtime kotlin exceptions you really don't expect.

    If I remember correctly I had a lot of issues when overloading Fragment class and methods related to View creation.