My react native app (running on Android) is restarting whenever Bluetooth headphones are connected or disconnected. Why is this happening and how can I prevent it?
I'd expect the app to remain open when Bluetooth headphones are connected or disconnected, but instead the app restarts (the 'activity is recreated' in Android lingo).
I've tried altering the manifest by adding this line, but it didn't fix the issue:
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
A bit overkill, but I tried adding even more BT related permissions, which still didn't fix the issue:
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
What am I missing?
Environment:
- React-native: 0.66.2
- Android OS: 12
- Device: Pixel 4
I found the solution with the help of this answer to a similar question.
It looks like Bluetooth headphones (and maybe other devices) when connecting / disconnecting trigger a configuration change which causes Android to recreate the activity by default.
You can override the default behaviour by editing the
configChange
attribute in the AndroidManifest.xml file. The full list of valid values for this attribute are on this Android developer page – the specific configChange value in my case was "navigation".To override the default behaviour I edited the
android:configChanges
line in AndroidManifest.xml to includenavigation
:This was tested on Android 10 and 12 and works on both – the app no longer restarts when connecting / disconnecting Bluetooth headphones : )
NOTE: none of the additional permissions I tried were needed in the end. The
configChanges
solution works fine without them.