0

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?

gkris
  • 1,209
  • 3
  • 17
  • 44

1 Answers1

1

You can get the last know location from using the getLastKnownLocation(LocationManager.GPS_PROVIDER) or the getLastKnownLocation(LocationManager.NETWORK_PROVIDER). If you want to register for location updates that will be a little bit more tricky. I would call

requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener)

from 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?

Community
  • 1
  • 1
Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82
  • Hi. thanks for the reply. Unfortunately I already have the getLastKnownLocation methods. Well I only want the location fix once, so I did not use the listener in a persistent class. I thought an async class listener would be enough. – gkris Jun 13 '12 at 23:57
  • The problem is that when you get the location via the onLocationChanged(Location location) method how do you communicate with the Activity that you have a new location. Since you are unsure of what Activity will be displayed hence the need for some persistent class. You might be able to unregister for location updates in the on activity and then register in the next activity. I am not sure if it will start the process all over again. – Stefan Bossbaly Jun 14 '12 at 00:01
  • I pass on the values using variables. I will try to do it using persistent class, thanks for the suggestion. – gkris Jun 14 '12 at 00:03