'Finding if external usb or bluetooth keyboard attached in Android

Can anyone please tell me if there is any way we can find out if a bluetooth QWERTY keyboard is attached to android device.

I tried working with getResources().getConfiguration.keyboard, but it always gives me the same value whether key board is attached or not.

Thanks



Solution 1:[1]

One way to do this is adding android:configChanges="keyboard" to the activity in your AndroidManifest.xml file.

With this you can override onConfigurationChanged which will be called whenever a keyboard is plugged in or plugged out

 @Override
 public void onConfigurationChanged(Configuration newConfig) 
 {
   if(newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        //A hardware keyboard is being connected
   }  
   else if(newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES)
       //A hardware keyboard is being disconnected
   }

 }

Solution 2:[2]

An improvement to @LeonLucardie's answer, in Kotlin.

Manifest (as per @MobileMon's comment):

<activity
    android:configChanges="keyboard|keyboardHidden"

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    when (resources.configuration.hardKeyboardHidden) {
        HARDKEYBOARDHIDDEN_NO -> Log.d(TAG, "A hardware keyboard is connected.")
        HARDKEYBOARDHIDDEN_YES -> Log.d(TAG, "A hardware keyboard is disconnected.")
    }
}

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)

    when (newConfig.hardKeyboardHidden) {
        HARDKEYBOARDHIDDEN_NO -> Log.d(TAG, "A hardware keyboard is being connected.")
        HARDKEYBOARDHIDDEN_YES -> Log.d(TAG, "A hardware keyboard is being disconnected.")
    }
}

Note: calling super.onConfigurationChanged(newConfig) seems to be mandatory.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leon Lucardie
Solution 2 hata