I’ve been trying to get display a compass and a distance between my position and another position on the map.
Almost exactly like:
Android: compass + distance in a listview
I understood the code, set up a listener for detecting orientation changes, and also calculated the distance.
Furthermore, I am displaying the correct distance in my ListView (I already had a custom adapter). Thats a little clarification as to where I am.
This is my problem: I am updating the ListView every second through the listener, by changing the values of the actual list the adapter is looking at and calling:
notifyDataSetChanged();
Calling this every second is making the ListView laggy, just as I had expected. I can get away with updating the distance every 10 seconds or so (or a little more). However, I have to update the list far more often to have a live compass as well. I’ve been looking around and I couldn’t really find anything, I would appreciate all the help I can get. Thank you!
Side note: If you need to see any code I’ve written, I’m willing to paste it here. There are many parts to it so I will do it on demand.
IMHO you should omit the whole list view and adapter. The best approach would be creation of own view for elements which should be updated frequently.
For example create view called HeadingView which will have setAbsouluteheading. This setter would be used by adapter. Then view would implement also SensorEventListener to observe sensors and get device heading.
When relative direction should change HeadingView would update it self. Problem in this case is detection when HeadingView should register/unregister itself for sensor events. onWindowFocusChanged looks promising and onWindowSystemUiVisibilityChanged (API level 16) is what you need.
Remember that there is a danger that there may be some corner cases and your view will not unregistered itself from observing sensors when it should. This may lead to terrible power consumption in sleep mode, so remember to do extensive testing.
There are probably alternative ways to perform communication between this HeadingView and sensors, but I think in general my concept is good solution.
Update:
I’ve come up with better idea how to communicate with this HeadingView without problems to detecting when disable sensors and not causing memory leak. The answer is week reference or more exactly WeakHashMap.
HeadingView view is more or less as I explained before, but in constructor it notifies YourActivity about its existence. So it would bes something like that:
And your activity:
Standard sensor handling in activity now applies so detecting when to disable sensor is not a problem and you don’t have to worry about memory leaks. I suspect that even you don’t have to alter code a lot :).
To make it nicer you can define interface.