Search code examples
androidkotlinandroid-intentservice

Kotlin how to put extra from Activity to Service


I think I now how to put extras, but don't know how to get them

Intent(this, MyService::class.java).also { intent ->
    bindService(intent, connection, Context.BIND_AUTO_CREATE)
    intent.putExtra("ip1", ip1)
    intent.putExtra("port1", port1)
 }

I tried with something like val ip1 = getIntent().getStringExtra("ip1") but it doesn't work, it also says getIntent() is deprecated and to use parseUri instead.


Solution

  • Place the intent parameters before binding to the service:

    val intent = Intent(this, MyService::class.java)
    intent.putExtra("ip1", ip1)
    intent.putExtra("port1", port1)
    bindService(intent, connection, Context.BIND_AUTO_CREATE)
    

    And use the intent from the service's onBind method to get the values back:

    override fun onBind(intent: Intent): IBinder? {
        val ip1 = intent.getStringExtra("ip1")
        val port1 = intent.getStringExtra("port1")
        ...
    
        return binder
    }