Download Code

Android GPS Location

In this tutorial you will learn how to get android gps location using Service,Location and Location Manager in android application.Let me give you some information about them.

GPS

Global Positioning System is a network of orbiting satellites that send precise details of their position in space back to earth.

Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.Callback methods of a service.

  • onStartCommand()
  • onBind()
  • onCreate()
  • onDestroy()

Location

Location class gives geographic location.It contains latitude and longitude etc.

Location Manager

Location Manager provides access to the system location services.For more detail visit Developers site.

Location Listener

Location Listener used for receiving notifications from the LocationManager when the location has changed.

Now create new android application project.Go to your activity_main.xml and add following components.

  • Four TextViews
  • Button

android gps location,gps,location,location manager,location listener,locatio manager android,location android tutorial,gps location android,android app tutorial,latitude,longitude,how to use gps in android,how to get location in android,gps location tutorial android

Now go to MainActivity.java class.Do the following steps.

  • Create variables for Two TextView and button.
  • Refer their id’s
  • Apply click event on button using onClickListener Interface.

MainActivity.java

package developer.codecgps;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

	
	TextView userLatitude,userLongitude;
	Button getUserLocation;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
        
    }

    public void initialize(){
    	userLatitude = (TextView) findViewById(R.id.lati);
    	userLongitude = (TextView) findViewById(R.id.longi);
    	getUserLocation = (Button) findViewById(R.id.location);
    	getUserLocation.setOnClickListener(this);
    }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.location:	
			break;
		}	
	}  
}

After that create new class GPS.java.Now do the following steps.

  • Extends GPS.java class with Service class.
  • Add unimplemented methods of Service class.
  • Implements LocationListener Interface and add unimplemented methods.
  • Create variables for gps,network,connection_getter,Context,Location Manager and Location.
  • Create constructor with context as a parameter.
  • Create method like getUserLocation() to get latitude and longitude.
  • Some other methods to get the location.
  • Create alert dialog to enable service(GPS,Network) setting.

Android GPS location services class.

GPS.java

package developer.codecgps;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPS extends Service implements LocationListener{

	private final Context con;     // pointer this class means context(this)
	boolean GPS_Status = false;     // GPSstatus variable activated or not
	boolean Network_Status = false; // Network service status checker
	boolean able_To_Get_Location = false;   // status to check whetherGPS or Network gives the location
	Location location;                    // location variable through which we will get latitude and longitude

	private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // The minimum distance to change Updates in meters
	private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // The minimum time between updates in milliseconds
	protected LocationManager locationManager; // Location Manager variable
	double latitude; // latitude
	double longitude; // longitude
	// constructor for GPSclass to set the context and get user location
	public GPS(Context con){
		this.con = con;
		getUserLocation();
	}
	// called this method when location changes
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		this.location = location;
		getLatitude();
		getLongitude();
	}
	// called this method when location changed like service not available etc.
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


	public Location getUserLocation(){
		try{
			locationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE);

			// getting GPS status
			GPS_Status = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

			// getting network status
			Network_Status = locationManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

			if (!GPS_Status && !Network_Status) {
				// no network provider is enabled
			} else {
				this.able_To_Get_Location = true;
				// First get location from Network Provider
				if (Network_Status) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER,
							MIN_TIME_BW_UPDATES,
							MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
					Log.d("Network", "Network");
					if (locationManager != null) {
						location = locationManager
								.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
						if (location != null) {
							latitude = location.getLatitude();
							longitude = location.getLongitude();
						}
					}
				}
				// if GPS Enabled get lat/long using GPS Services
				if (GPS_Status) {
					if (location == null) {
						locationManager.requestLocationUpdates(
								LocationManager.GPS_PROVIDER,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
						Log.d("GPS Enabled", "GPS Enabled");
						if (locationManager != null) {
							location = locationManager
									.getLastKnownLocation(LocationManager.GPS_PROVIDER);
							if (location != null) {
								latitude = location.getLatitude();
								longitude = location.getLongitude();
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return location;
	}

	// Stopping
	public void stopUsingGPS(){
		if(locationManager != null){
			locationManager.removeUpdates(GPS.this);
		}       
	}

	/**
	 * Function to get latitude
	 * */
	public double getLatitude(){
		if(location != null){
			latitude = location.getLatitude();
		}

		// return latitude
		return latitude;
	}

	/**
	 * Function to get longitude
	 * */
	public double getLongitude(){
		if(location != null){
			longitude = location.getLongitude();
		}

		// return longitude
		return longitude;
	}

	// check wifi and GPS status working or not
	public boolean able_To_Get_Location() {
		return this.able_To_Get_Location;
	}
	// alert to enable your GPS or Network setting
	public void showSettingsAlert(){
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(con);

		// Setting Dialog Title
		alertDialog.setTitle("GPS is settings");

		// Setting Dialog Message
		alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

		// On pressing Settings button
		alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int which) {
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				con.startActivity(intent);
			}
		});

		// on pressing cancel button
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		// Showing Alert Message
		alertDialog.show();
	}
}

Next create variable/object of GPS class in MainActivity.java.Get the location and set to textview.

MainActivity.java

package developer.codecgps;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

	GPS myGPS;     // android GPS location class variable
	TextView userLatitude,userLongitude;
	Button getUserLocation;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
        myGPS = new GPS(this);  // initializing android GPS location class
    }

    public void initialize(){
    	userLatitude = (TextView) findViewById(R.id.lati);
    	userLongitude = (TextView) findViewById(R.id.longi);
    	getUserLocation = (Button) findViewById(R.id.location);
    	getUserLocation.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.location:
			if(myGPS.able_To_Get_Location()){
				double codecLatitude = myGPS.getLatitude();
				double codecLongitude = myGPS.getLongitude();
				userLatitude.setText(Double.toString(codecLatitude));
				userLongitude.setText(Double.toString(codecLongitude));
				Toast.makeText(getApplicationContext(), Double.toString(codecLongitude), Toast.LENGTH_SHORT).show();
				Toast.makeText(getApplicationContext(), "Location Successfully Set", Toast.LENGTH_SHORT).show();
				
			}
			else{
				myGPS.showSettingsAlert();
			}
			break;
		}
		
	}
   
}

Now go to Android Manifest.xml and add ACCESS_FINE_LOCATION permission.
Now run android application project.

android gps location,gps,location,location manager,location listener,location manager android,location android tutorial,gps location android,android app tutorial,latitude,longitude,how to use gps in android,how to get location in android,gps location tutorial android
That’s it for this tutorial.
Thanks.