androidusb-otgandroid-usb

Activity onCreate() called when connecting OTG device


I am developping an app which uses a OTG USB device.

The device I am using is a USB barcodescanner which is detected by android as a keyboard.

But I detected that every time I plug or unplug the OTG device, the App is restarted by calling the Activity onCreate() method.

This is causing me a lot of problems because I cannot detect why is the onCreate() method being called.

Is there any Intent or anything that could be fired and to be catched when the otg device is plugged / unplugged?

Thanks in advance.


Solution

  • android is restarting your activity because of the configuration change, see documentation here.

    to make sure this is the case for you try adding android:configChanges="keyboard" to your activity's entry in the manifest file. This will tell android not to restart the activity when a keyboard is plugged in. After that, onCreate() should no longer be called when plugging in the device.

    note that you shouldn't use that as a fix, it is just a way to make sure that this is the case for you (and it is not a specific thing in your code). you have to deal with the activity restart as it is normal behavior in android and shouldn't cause problems with your application. One common cause for the activity restarts is orientation changes, and it is very discouraged to use the approach above in solving it, your activity shouldn't have any problems when android wants to restart it, see this answer for more information.