Why can't I bind a Service() in Application() using this in Android Studio project?

124 Views Asked by At

I try to bind a service named ServiceRecord in class UIApp, in Code A , I get the following error when I try to invoke fun bindService( ) {...}, why ?

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

But Code B can work well when I invoke fun bindService( ) {...}.

Code A

@HiltAndroidApp
class UIApp : Application() {
    private var serviceRecord: ServiceRecord? = null

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
            val binder = iBinder as ServiceRecord.MyBinder
            serviceRecord = binder.serviceRecord
        }
        ...
    }

    fun bindService(  ) {
        Intent(this, ServiceRecord::class.java).also { intent ->
           this.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }

}

@AndroidEntryPoint
class ServiceRecord: Service() {
   
    inner class MyBinder : Binder() {
        val serviceRecord: ServiceRecord
            get() = this@ServiceRecord
    }

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

Code B

@HiltAndroidApp
class UIApp : Application() {

    companion object {
        lateinit var appContext: Context
    }

    override fun onCreate() {
        super.onCreate()
        appContext = applicationContext
    }

    private var serviceRecord: ServiceRecord? = null

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
            val binder = iBinder as ServiceRecord.MyBinder
            serviceRecord = binder.serviceRecord
        }
        ...
    }

    fun bindService(  ) {       
        Intent(appContext, ServiceRecord::class.java).also { intent ->
            appContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }
}

... //The same
0

There are 0 best solutions below