GPS in an AsyncTask in Android

I recently encountered the need to have an AsyncTask in an Android app that gets the current GPS position, then fetches some data from the network upon getting the position. This isn’t very straightforward to do, since the GPS stuff uses a callback driven model. I did a quick search and came up with a lot of Stack Overflow solutions to the problem that were really bad. Most of them suggested launching a GPS request, then having some sort of loop that spins until the location comes in. At least one of them didn’t even have any sort of delay in the loop, making it burn up your phone’s battery while it waited.

It turns out to be pretty simple to solve this problem, using the Looper class, which is a bit of a confusing thing. The looper will establish a loop which waits for events/messages within the AsyncTask thread. Once the position comes in, you have the code exit the loop, and then continue on with your network request. Here’s the basic idea:

Advertisements

2 thoughts on “GPS in an AsyncTask in Android

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s