Android Location using GPS, Network Provider

Last modified on August 1st, 2014 by Joe.

GPS and network providers are two different ways to get Android device location (latitude and longitude). GPS and network location providers have got their own advantages and we may have to use both in sync. In in-door situations GPS may not provide the location quickly and network location provider is quick. Network location provider uses our mobile connectivity provider and will give the nearest tower location. GPS gives the exact location of where we are standing.

Having said all the above, I just noticed that I have written an Android GPS tutorial already. Though I feel like a buffoon, somehow I have to manage now. Its okay, it will do no harm if we have two different examples for the same purpose.

There is not much we need to do, Android API takes care of everything. We need to implement LocationListener and make it a service class by extending Android Service API. Then use the Android’s LocationManager API to get the latitude and longitude location. Nothing much to discuss, lets jump into the code.

AppLocationService.java

We can use the onLocationChanged() method to continuously monitor/get the device location. 

package com.javapapers.android.androidgps;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class AppLocationService extends Service implements LocationListener {

	protected LocationManager locationManager;
	Location location;

	private static final long MIN_DISTANCE_FOR_UPDATE = 10;
	private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

	public AppLocationService(Context context) {
		locationManager = (LocationManager) context
				.getSystemService(LOCATION_SERVICE);
	}

	public Location getLocation(String provider) {
		if (locationManager.isProviderEnabled(provider)) {
			locationManager.requestLocationUpdates(provider,
					MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
			if (locationManager != null) {
				location = locationManager.getLastKnownLocation(provider);
				return location;
			}
		}
		return null;
	}

	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

}

AndroidLocationActivity.java

This is the main activity having two buttons, each for GPS and Network provider. Used a toast to show the message and if the GPS or Network or not enabled in the device then we show an alert with a shortcut to the settings.

package com.javapapers.android.androidgps;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidLocationActivity extends Activity {

	Button btnGPSShowLocation;
	Button btnNWShowLocation;

	AppLocationService appLocationService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		appLocationService = new AppLocationService(
				AndroidLocationActivity.this);

		btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
		btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {

				Location gpsLocation = appLocationService
						.getLocation(LocationManager.GPS_PROVIDER);

				if (gpsLocation != null) {
					double latitude = gpsLocation.getLatitude();
					double longitude = gpsLocation.getLongitude();
					Toast.makeText(
							getApplicationContext(),
							"Mobile Location (GPS): \nLatitude: " + latitude
									+ "\nLongitude: " + longitude,
							Toast.LENGTH_LONG).show();
				} else {
					showSettingsAlert("GPS");
				}

			}
		});

		btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
		btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {

				Location nwLocation = appLocationService
						.getLocation(LocationManager.NETWORK_PROVIDER);

				if (nwLocation != null) {
					double latitude = nwLocation.getLatitude();
					double longitude = nwLocation.getLongitude();
					Toast.makeText(
							getApplicationContext(),
							"Mobile Location (NW): \nLatitude: " + latitude
									+ "\nLongitude: " + longitude,
							Toast.LENGTH_LONG).show();
				} else {
					showSettingsAlert("NETWORK");
				}

			}
		});

	}

	public void showSettingsAlert(String provider) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				AndroidLocationActivity.this);

		alertDialog.setTitle(provider + " SETTINGS");

		alertDialog
				.setMessage(provider + " is not enabled! Want to go to settings menu?");

		alertDialog.setPositiveButton("Settings",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						AndroidLocationActivity.this.startActivity(intent);
					}
				});

		alertDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		alertDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Android-Location-GPS-Network-Activity

AndroidManifest.xml

Android manifest file is important here. Just note the “uses-permission” tag below. We need to those tags for accessing GPS and network provider.

<?xml version='1.0' encoding='utf-8'?>
<manifest package="com.javapapers.android.androidgps" xmlns:android="http://schemas.android.com/apk/res/android" android:versioncode="1" android:versionname="1.0">

    <uses-sdk android:minsdkversion="8" android:targetsdkversion="18" />

    <!-- to get location using GPS -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
	<!-- to get location using NetworkProvider -->
    <uses-permission android:name="android.permission.INTERNET" />

    <application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:allowbackup="true">
        <activity android:name="com.javapapers.android.androidgps.AndroidLocationActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Android GPS Network Provider Output

Android-GPS-Location

If GPS or Network setting are not enabled:

Enable-GPS-Network-Settings-in-Android

Android-Enable-Location-Access

Download GPS Location Android Project

Download the project: AndroidLocation using GPS and NW Provider: Android Project

Comments on "Android Location using GPS, Network Provider"

  1. issac balaji says:

    sir,
    can you explain how we can set on GPS by code instead of asking user to set on GPS

  2. Malcom says:

    Thanks a lot for this.

  3. Pratik says:

    Thanks Joe

  4. Rakhi Dhavale says:

    helpful! thanks!

  5. murali says:

    how to find the locaton mobile destiontion

  6. Mayur says:

    Hi,
    I have download your project sir,
    but i’m getting longitute and latitude properly,
    but i’m unable to get GPS location.
    how can i solve this???????
    Please reply……
    Thanks in advance.

  7. kalaiyarasi.p says:

    dear sir,
    i would like to get information about android project,like android location using gps-network provider,how to find friend location during call how to get he/she location through message?

  8. Clan says:

    Google does not allow programs to change GPS settings. This is why your program has to ask the user to change the settings.

  9. kishor says:

    i export apk and tested on my phone it showing the location using network provider but not by gps provider even i enable gps settings in my phone. Please help me to solve this.

  10. Rom says:

    Hi, is there any link I can download this app (.apk) for me to run on my smartphones?
    Thanks.
    Best Regards,
    Rom

  11. Rom says:

    Hi Kishor,

    Could you kindly share your .apk file with me, so I can run it on my smartphone?
    Thanks.
    Best Regards
    Rom

  12. pragadees says:

    Hi joe,
    How to get a friends location latitude and longitude please help me

  13. Vishal Bhandare says:

    Thank you. This blog helps me a lot.

  14. sani says:

    Hi,
    I am working on an application where the app sends location to a fixed mobile number after a given interval of time, say 10 mins.
    Apart of these the app once started cannot stop ending message till the user specifies the same explicitly by pressing a button, i.e. it works in sleep and even if the phone has restarted.

  15. santhi says:

    hi,
    how to get address along with latitude and longitude.please tell me how to modify your program for that output?

  16. Anonymous says:

    yeeees!

    thanks a lot!

Comments are closed for "Android Location using GPS, Network Provider".