I am developing an application where I am streaming live sensor data via bluetooth, then have several Activities that can work on this live stream of data to display it in different ways (e.g. statistics, histogram, trend charts etc.)
I need to maintain the bluetooth link across Activities, and I also need to maintain receiving the data into a buffer across Activities (e.g. you can be viewing the data in the trend chart activity, then hop across into a statistics Activity without it clearing the data.)
How I've done it is to extend application and have it hold a custom class which holds all the relevant Bluetooth objects (bluetooth device, IOstreams.) Then when the user initiates the connection through the front page Activity, the bluetooth connection is opened and a service is started that reads the data from the input stream, converts it and stores it into a arraylist. Then any of the display Activities work on this ArrayList.
That works great. But I can't work out how to close the bluetooth connection and service when the application is either killed, or placed into the background. As it's important to ensure the bluetooth connection is closed properly, or else it can be difficult to re-establish a connection.
About the best I've come up with so far is to implement a task transition timer as described in this post https://stackoverflow.com/a/15573121/3015368, and have it close the connection and service if the timer completes.
I was hoping there might be a better way of doing this?