3

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.

Hermandroid
  • 2,120
  • 4
  • 29
  • 35

1 Answers1

9

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.

Community
  • 1
  • 1
Mike
  • 8,055
  • 1
  • 30
  • 44
  • Thank you Mike, I checked the links you suggested me. I'll try to restore the states when the configChanges occur.But I have a dumb question. So, I coul put all of my variables on a headless fragment with setRetainInstance(true) and, obviously, I could recover it when the onfigChange occurs. But, before fragments existed, how the hell you could recover variables. – Hermandroid Apr 16 '16 at 13:54
  • you don't need to use fragments if your variables are Parcelable. If so you can override `onSaveInstanceState`, save your variables in the bundle there, then later restore it using the bundle passed to your `onCreate` see [this](http://developer.android.com/training/basics/activity-lifecycle/recreating.html). – Mike Apr 16 '16 at 14:05
  • @Herman , If your variables cannot be saved by the bundle (eg. they are `Socket`s,`Thread`s, or `AsyncTask`s), then fragments are currently the way to go. Before fragments people could use the deprecated `onRetainNonConfigurationInstance()`. see [this](http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html). – Mike Apr 16 '16 at 14:09
  • Thank you so much @Mike. Really appreciate your help. It is working now. I only need yo put my variables on the bunle. – Hermandroid Apr 16 '16 at 14:50