0

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?

Community
  • 1
  • 1
Harvs
  • 34
  • 1

1 Answers1

0

you can stop services by making an intent which points to ur service class and call this function if your service is running it kills it if its not running then it wont do anything

stopService(/* intent name*/)

u can do that in onPause() method which is automatically called when ur app goes to the background then if you need to restart the service u can call onResume() which is also automatically called when ur app gains focus

hence: u need to override onPause() and onResume() methods.

  • The problem is, onPause and onResume are called on each Activity when it switches between them. I need to keep the connection alive, and only close it when the application (not an individual activity) is killed or backgrounded. – Harvs Nov 21 '13 at 00:39
  • please go to this question [link](http://stackoverflow.com/questions/9099598/android-detect-when-an-application-as-a-whole-not-individual-activities-is-pa) its the same as yours and try the answer – Tarek Kanon Nov 21 '13 at 02:34