14

Bluetooth keyboard will cause activity destroy and recreate if I turn off it or far away from pad(Android) Activity will be recreate how can i avoid this problem

4 Answers4

27

In contrast to the accepted answer, I found that keyboard|keyboardHidden was not enough. I was working with a Logitech Bluetooth keyboard (model #JNZYR0021).

What did work was this:

<activity
  ...
  android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation"
/>

Apparently this Logitech keyboard also changes navigation, which is weird because the Android docs say:

The navigation type (trackball/dpad) has changed. (This should never normally happen.)

Go figure.

Community
  • 1
  • 1
nlawson
  • 11,510
  • 4
  • 40
  • 50
19

Pairing a Bluetooth keyboard is considered to be a configuration change: Try adding the below to your AndroidManifest.xml

android:configChanges="keyboard|keyboardHidden"

From: http://developer.android.com/guide/topics/manifest/activity-element.html#config android:configChanges

Schleir
  • 1,775
  • 2
  • 15
  • 14
0

In my case, add keyboard|keyboardHidden|navigation is not enough, the Activity is still recreated. I tried to figure out a general way to find the reason to the configuration change.

The first thing need to do is add all of the cause of config change in the Activity's configChanges to make sure your Activity won't be recreated under your situation. Then override your Activity's method OnConfigurationChange(), use Configuration.diff() to calculate the difference between your newConfig and the current one(You can get it from getResources().getConfiguration()). The result is an decimal, transfer it to be a hexadecimal and calculate how is combined by the constants name starts with CONFIG_ in ActivityInfo.

For example, the configuration diff is 112 in decimal, and its hex is 0x70. In this case, we have CONFIG_KEYBOARD = 0x0010;, CONFIG_KEYBOARD_HIDDEN = 0x0020, CONFIG_NAVIGATION = 0x0040, which means these three flags are changed during this configuration change.

Steve
  • 1
0

For me, adding "orientation|screenSize|keyboard|keyboardHidden|navigation" to configChanges would still call onDestroy and onCreate of the activity. After a long research I found this article: https://developer.samsung.com/sdp/blog/en-us/2017/12/07/samsung-dex-lifecycle-on-switching-between-mobile-and-samsung-dex-mode

Basically, if you use Lenovo's productivity mode or Samsung DeX, it would recreate the app nonetheless, so it's necessary to add all of these if you want for the app to not recreate itself when you add a physical/bluetooth keyboard.:

<activity android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|uiMode|density">

Also, add this for Samsung DeX inside your AndroidManifest:

<meta-data 
android:name="com.samsung.android.keepalive.density" 
android:value="true" />