I have a login page (an activity in Android), during which I run an async task to get the location fix. Soon after the login is successful, I redirect the App into another activity. The location fixes are not available after i switch to the next activity. Here is how it goes:-
code:-
oncreate {
...
AsyncTaskClass task;
task.execute();
}
class AsyncTaskClass extends Async... {
doInBackground () {
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
}
onPostExecute {
//disable listener
startActivity(nextPage);
}
}
I can see that the location fix is requested by the App (GPS icon shows up in the taskbar), but within a moment, the postExecute() is executed, nextPage loads and location fixes are not obtained. How do I make sure that the location fixes will be obtained? In other words, even if I change the activity, how to make sure that the location is received in the background?
You can get the last know location from using the
getLastKnownLocation(LocationManager.GPS_PROVIDER)or thegetLastKnownLocation(LocationManager.NETWORK_PROVIDER). If you want to register for location updates that will be a little bit more tricky. I would callfrom a persistent class in your app. In mine I have a class called location manager. When the location manager gets the location update then send the location to the Activity via a callback method that is implemented using an interface. Take a look at this question …
What is the simplest and most robust way to get the user's current location on Android?