Search code examples
androidmultithreadingservicebackgroundlifecycle

Android background task and lifecycle


I'm currently working on an app that connects to a bluetooth device and receives a message every .25 seconds, then displays that data on screen. The user will also be able to arbitrarily start/stop logging this data to a file on the SD card.

I have tried extending a thread class that listens for the messages from the BT device, and then using a handler to send the data back to the UI thread and display it.

This was working fine, but on configuration changes, like screen rotation, when the activity is destroyed and re-created the BT thread is duplicated and I can no longer communicate with it. I have no problems, if I stop the BT thread in onStop() and re-start it in onResume() but then I need to re-connect to the BT device and if the user was logging data, that would be inturrupted.

What is the correct way to accomplish this functionality? Is there a way to setup my thread so it isn't duplicated or so I can re-connect to it after a config change? Should I instead be looking at a service for my BT connection and logging, and then somehow get a feed from the service to display on the UI?

Thanks!


Solution

  • Should I instead be looking at a service for my BT connection and logging, and then somehow get a feed from the service to display on the UI?

    Yes you should. I think this is a good approach. You should run your thread the logs data in a service, and put the data that needs to be passed to the main UI or activity in a sharedpreference which will give ANY activity access to the information.

    I think this would be the best way to go about doing this.

    OR

    You could use the method provided by alex.veprik