Android GPS Location Manager - Androhub

GPS Location

Android GPS Location Manager

If you are developing any location based app, you can make your app more smarter by finding user’s location automatically. For this you need to integrate location modules in your application. You can learn more about location strategies.

Example

In this tutorial, we are going to learn how to get user location using GPS location manager with and without internet.

Video Demo

1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.

3. Open AndroidManifest.xml and add ACCESS_FINE_LOCATION (Which includes both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION). Also we have to detect internet connection so we need ACCESS_NETWORK_STATE this permission also.

4. Now create a xml layout containing two button and two textview to display location using internet and without internet.

5. Create a new java class naming ConnectionDetector.java to detect Internet connection. If you don’t no how to detect internet connection then you can check my tutorial here.

6. Now, create a new java class naming GPSService.java extending Service also implement this class from LocationListener and add the following code.

Add the implementation for the function geoLocation() which was called in the constructor. In this function we’ll get the location from network provider first. If network provider is disabled, then we get the location from GPS provider.

This method will return the complete address.

This methods used to getLongitude, getLatitude and closeGPS.

If GPS is not enabled then prompt user to enable GPS via this method.

Final Source code.

7. Now, create a new java class naming GPSLocation.java. This class contains methods like turnOn ,turnOff GPS and getLocation that we will use in our activity.

8. The above two classes are used to get location in presence of internet but in absence of internet we have to do something else. I am using this method to get current location in latitude and longitude.

9. Finally come to your MainActivity.java and add the following code. In this activity we are getting current location via internet and without internet. While getting location through internet we have to check first if internet is present or not. So for this I used ConnectionDetector class to get network status.

10. Now, you are all done. If you run your app in emulator you will get longitude and latitude but if you run it over real device you will get proper address (in case of internet).

Thanks. :)

 

Post comment

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