I think I already know the answer to this question because it seems, uh, will uh a bit far fetched. But I am seriously looking for a solution.
Suppose that I have an Activity, call it Bluetooth activity, that starts a bluetooth background thread and the thread runs forever even when the Bluetooth Activity goes away – yes it really does run forever. This bluetooth background thread is a data acquisition thread that continually collects data to be plotted by an Activity, call it Plot activity, in real-time. We can refer to the plotting method as a static method called Plot.plotData();
My problem is I can’t tell when the Plot activity is active, so I cannot tell when to start calling Plot.data(). You might think that since Plot.plotData() is a static method I can call it anytime I want. But not so. I have to wait until Plot is instantiated through Intent() and startActivity. Otherwise Plot’s onCreate() method has not been called and Plot is full of null pointers.
How do I solve this problem. Add a static getter/setter that is initially false until onCreate is run?
It will not, unless you put it in a
Service. Do not leak threads from anActivity, please.Please note that you have been told this already.
This should not be a static method, as I told you before.
Which is why the
Plotactivity should be responsible for its own drawing. Your background thread in yourServiceshould solely be handling data collection. You can arrange to get the data from theServiceto thePlotactivity via aMessenger, or viabindService()and a callback, or other means.The design of a service doing the data collection and activities displaying the results is pervasive in Android. Email clients use services to collect new email messages. Feed readers use services to collect the latest feed updates. And so on. You just happen to be collecting information via Bluetooth, whereas most of the examples of this concept will collect information over the Internet.
So, to recap: move your Bluetooth data collection logic into a
Service, using a background thread (or threads, plural, if needed). Arrange for theServiceto deliver the data to thePlotactivity as it arrives. Have thePlotactivity display the results.