CompanionDeviceService unbinds immediately

848 Views Asked by At

I'm trying to implement CompanionDeviceService in order to interact with our BLE device. According to the documentation

System will keep this service bound whenever an associated device is nearby, ensuring app stays alive

But that's not what I'm seeing

17:47:48.563 MyCompanionDeviceService: onDeviceAppeared FF:FF:6D:10:F1:16
17:47:48.565 MyCompanionDeviceService: onUnbind
17:47:48.568 MyCompanionDeviceService: onDestroy

Around 1 minute later, onDeviceAppeared is invoked again, with the same result.

FF:FF:6D:10:F1:16 is not bonded. createBond is never invoked on BleDevice. I haven't found whether this is relevant or not.

I'm running on a Pixel 4a on latest available Android 12 version

Edit: Adding more code for reference

Manifest

<uses-permission android:name="android.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_USE_DATA_IN_BACKGROUND" />
<uses-permission android:name="android.permission.REQUEST_OBSERVE_COMPANION_DEVICE_PRESENCE" />


<service
  android:name="com.mycompany.MyCompanionDeviceService"
  android:exported="true"
 android:permission="android.permission.BIND_COMPANION_DEVICE_SERVICE">
      <intent-filter>
        <action android:name="android.companion.CompanionDeviceService" />
      </intent-filter>
</service>

The startObservingDevicePresence succeeds, otherwise my service wouldn't be called at all

And there's nothing relevant on the service

@RequiresApi(Build.VERSION_CODES.S)
internal class MyCompanionDeviceService : CompanionDeviceService() {   

    override fun onCreate() {
        appComponent.inject(this)
        super.onCreate()
    }

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

    override fun onDeviceAppeared(address: String) {
        Timber.d("onDeviceAppeared $address")
    }    

    override fun onDeviceDisappeared(address: String) {
        Timber.tag("companionservice").d("onDeviceDisappeared $address")
    }

    override fun onDestroy() {
        super.onDestroy()

        Timber.d("onDestroy")
    }
}
2

There are 2 best solutions below

0
On

MyCompanionDeviceService: onUnbind means the system unbinds your MyCompanionDeviceService. unbind here is not related to your device binding.

2
On

It's intended behavior for MyCompanionDeviceService to spin up call onDeviceAppeared and then be destroyed.

What you want to do is start something else that will run for longer in order to do whatever operation you are trying to do. For example you could open your main activity or start a foreground service. Then that would run the code you want to run.