How To Get User’s Current Location In Android

When I searched in Google on how to get the current location in Android, I came across ┬áthe page in Android’s documentation about connecting to Google Play Services and initializing it.

I found out this was really not needed. If I could get the location without having to use this, all the better right?

User MrJre from the StackOverflow forum provided this very handy, useful, clean and non-Google Play Services type of code.

All you need are some broadcasters, receivers and listeners. This is how I did using some of his code. The code will try to get locations through GPS or WI-FI in case one or the other fails.

First off, place this code in a class.

Then create a broadcast class that will fire events to all listeners when a location has been found.

Next, create a listener for use in any Activity that may use location tracking.

All classes are now in place. The next thing to do is to implement the listener to your Activity.

In the onCreate() method, the fetchLocation() method is called and once a location is found, the broadcaster will fire the gotLocation() method to all listeners and return a Location object.

That’s it! And without having to use Google Play Services to get a location object.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *