Search code examples
androidbluetoothbroadcastreceiverandroid-serviceandroid-broadcast

How to send data from Android Service to its AIDL stub


I am developing a application to initiate the Bluetooth device application.

I have a service called MyService. I have stub MyServiceImpl to handle the AIDL interface which will be called from outside. I have broadcastreceiver to get the "ACTION_BOND_STATE_CHANGED".

My requirement is whenever device is connected(i.e device?.bondState == BluetoothDevice.BOND_BONDED, I need to send deviceinfo from Broadcast receiver to MyServiceImpl stub. The Reason - AIDL interface is already handled there, once the aidl is called, new class will be created from there. For that new class MyServiceImpl is needed. In addition, response to that interface call is sent through callbacks is also handled there.

The code is below. Can someone help me to send the device information from Broadcastreceiver to the Service stub Implementation?

class MyService : Service() {

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

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onCreate() {
       binder = MyServiceImpl()
       filterNewDevices()
    }

    private fun filterNewDevices() {
        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        registerReceiver(mBroadcastReceiverBond, filter)
    }

    private val mBroadcastReceiverBond: BroadcastReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent) {
            if (intent.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                if (device?.bondState == BluetoothDevice.BOND_BONDED) {
                    //HERE I NEED TO SEND THE device TO 
                }

                if (device?.bondState == BluetoothDevice.BOND_BONDING) {
                }

                if (device?.bondState == BluetoothDevice.BOND_NONE) {
                }
            }
        }
    }

    class MyServiceImpl : IBluetoothConnection.Stub(), IBinder {

        private lateinit var  btConnection: BTConnection

        override fun registerUuid(name : String?, uuid : String?, connectionId : Int, btDevice : BluetoothDevice?) {
                btConnection = BTConnection(this)
                btConnection.initialize(name!!, UUID.fromString(uuid), connectionId, btDevice)
            }
    }
}

Solution

  • Create a method in MyServiceImpl that takes the device as a parameter. In your BroadcastReceiver call the method on binder to pass the device to the service implementation.