I was playing around with the ADK and wondering how it would be possible to make the connection work while the app was in the background. The first way I tried was to not close the connection in onPause(). This worked, since the file input and output streams were able to continue … until they were garbage collected. When other Android apps run in the background, they use a Service. I tried this out with the ADK, and it works! Check out the video demonstration below.
The initialization and opening of the ADK is still done in the main activity. We use the Application class as a friendly singleton to transfer the streams, file descriptor, and usb accessory over to the Service.
When the Service is started, it creates an Updater thread, which runs every second.
Log.d(TAG, "updater not running");
updater =new Updater();
Log.d(TAG, "updater running");
In background, this can run for a very long time. I let it be for 12 hours before I stopped it.
However… there is a very bizarre bug. Sometimes when the app returns to foreground, it can’t reconnect to the ADK. The main problem is with the USB Manager trying to open the accessory for some reason. The app has permissions to the accessory, and it prints out the connected accessory correctly. Here is my trace of the bug: