pshashi04
pshashi04

Reputation: 242

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

Upvotes: 10

Views: 6166

Answers (2)

hata
hata

Reputation: 12478

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.

Upvotes: 0

Leon Lucardie
Leon Lucardie

Reputation: 9730

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
   }

 }

Upvotes: 19

Related Questions