问题
I am using the LocationManager to trace a user's location and show the same on GoogleMaps. I am using the following approach and have some questions regarding the same.
To get the user's location for the first time, I am using:
locationManager = LocationManager.getLocationManager();
location = locationManager.getCurrentLocation();
What I understand that this is a blocking call. Hence, I show an infinite progress bar till this method returns.
Once I have the location, I call a jsp page hosted on my server in a WebBrowser component and pass the lat and lng to this page. This page return a google map with the user's location as a marker.
I override the onLoad()
method of the WebBrowser to get an event when the page is loaded.
As soon as the page is loaded I assign a listener to my locationManager
to get location updates.
When I receive updates in the listener, I execute a javascript on the page using the BrowserComponent
-> execute()
method.
This approach is working very well.
The question:
When I query the LocationManager for the user's position for the first time, I am not explicitly assigning a listener. How does this method get executed internally ?
Does this start a listener of its own ?
If yes, then when I assign a listener in the onLoad()
method, does the initial listener get removed ?
Shall I explicitly clear the listeners to my locationManager ?
Or when I assign the listener, does it assign the earlier initiated listener ?
Will I end up having two listeners doing the same job ?
BR,
Sanket
回答1:
You are using the API correctly call to getCurrentLocation() or getLastKnownLocation() will return a Location object.(it may start a listener internally, but it will be stopped internally). When you call to setListener you should clear your listener when you don't want to get updates any more. (In either way you won't end up with 2 listeners)
Notice the getCurrentLocation() may return a less accurate Location object on Android, because if the gps is not available and/or not working it will default to the Network provider.
来源:https://stackoverflow.com/questions/20512619/proper-way-of-using-locationmanager-in-codename-one