I have simple activity with function that when called displays ble pairing request. After user confirms, startObservingDevicePresence("Some Mac address") is called. That successfully triggers CompanionDeviceService and I see logs that device appeared in range, but right after that onDestroy is called. App continues to run and there are no errors in logs. Has anybody used successfully these new android 12 api's (https://developer.android.com/guide/topics/connectivity/companion-device-pairing#keep-awake)?
MainActivity:
public class MainActivity extends ReactActivity {
private static final int SELECT_DEVICE_REQUEST_CODE = 42;
private static CompanionDeviceManager deviceManager;
private static AssociationRequest pairingRequest;
private static BluetoothDeviceFilter deviceFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
deviceManager = getSystemService(CompanionDeviceManager.class);
}
}
public void start() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
deviceFilter = new BluetoothDeviceFilter.Builder()
.build();
pairingRequest = new AssociationRequest.Builder()
.addDeviceFilter(deviceFilter)
.build();
deviceManager.associate(pairingRequest,
new CompanionDeviceManager.Callback() {
@Override
public void onDeviceFound(IntentSender chooserLauncher) {
try {
startIntentSenderForResult(chooserLauncher,
SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(CharSequence charSequence) {
}
},
null);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
try {
deviceManager.startObservingDevicePresence("Some MAC address");
} catch(DeviceNotAssociatedException e) {}
}
}
}
}
CompanionService:
@RequiresApi(VERSION_CODES.S)
public class BleCompanionDeviceService extends CompanionDeviceService {
private static final String TAG = "BleReceiver";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDeviceAppeared(@NonNull String s) {
Log.d(TAG, "DEVICE APPEARED INTO RANGE");
}
@Override
public void onDeviceDisappeared(@NonNull String s) {
Log.d(TAG, "DEVICE DISAPPEARED");
}
@Override
public void onDestroy() {
Log.d(TAG, "SERVICE DESTROYED");
}
}
This seems to be a race condition happening in CompanionDeviceManager, Android 13 should have fixed it.