Android GPS Using. How to get current location example

Hi. Here i want show you how to use Android GPS quickly. This is simple, may be not perfect example how to get current location by GPS.
To use GPS in your application first of all you must specify the uses-permission in Android manifest file:

<manifest>
    ...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    ...
</manifest>

If you don’t set this permission the application can’t get access to location service.

To use this application with android emulator you must mock location data. To do this using Eclipse you must:

  • Select Window > Show View > Other > Emulator Control
  • In Emulator Control panel enter the GPS coordinates under Location Controls and press Send

This operation you must do every time then you Run application.

Below you can see the application activity (HelloAndroidGpsActivity.java) source. Below you can download the source code of this Android project.
For more information about Android GPS Usage look HERE

package com.hrupin;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
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.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

	private EditText editTextShowLocation;
	private Button buttonGetLocation;
	private ProgressBar progress;

	private LocationManager locManager;
	private LocationListener locListener = new MyLocationListener();

	private boolean gps_enabled = false;
	private boolean network_enabled = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);

		progress = (ProgressBar) findViewById(R.id.progressBar1);
		progress.setVisibility(View.GONE);

		buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
		buttonGetLocation.setOnClickListener(this);

		locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
	}

	@Override
	public void onClick(View v) {
		progress.setVisibility(View.VISIBLE);
		// exceptions will be thrown if provider is not permitted.
		try {
			gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
		}
		try {
			network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
		}

		// don't start listeners if no provider is enabled
		if (!gps_enabled &amp;amp;amp;amp;&amp;amp;amp;amp; !network_enabled) {
			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle("Attention!");
			builder.setMessage("Sorry, location is not determined. Please enable location providers");
			builder.setPositiveButton("OK", this);
			builder.setNeutralButton("Cancel", this);
			builder.create().show();
			progress.setVisibility(View.GONE);
		}

		if (gps_enabled) {
			locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
		}
		if (network_enabled) {
			locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
		}
	}

	class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				// This needs to stop getting the location data and save the battery power.
				locManager.removeUpdates(locListener); 

				String londitude = "Londitude: " + location.getLongitude();
				String latitude = "Latitude: " + location.getLatitude();
				String altitiude = "Altitiude: " + location.getAltitude();
				String accuracy = "Accuracy: " + location.getAccuracy();
				String time = "Time: " + location.getTime();

				editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
				progress.setVisibility(View.GONE);
			} 
		}

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

		}

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

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if(which == DialogInterface.BUTTON_NEUTRAL){
			editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
		}else if (which == DialogInterface.BUTTON_POSITIVE) {
			startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
		}
	}

}

Download the source code. Here you can download the source code of this Android project.

24 thoughts on “Android GPS Using. How to get current location example

  1. Thanks, this was useful. Now all I have to do is send the location to the server and retrieve all the database entries within 10 miles. Simples. :)

  2. Thanks for share, but when i use your program, my phone don’t get location. In textview display: Sorry, location is not determined
    My phone turned on GPS, enable data (3G). I don’t unsderstand, location is null?
    If you know, plase help me
    Thanks

  3. Hi Igor Khrupin!
    when i run your new project. I submit ‘Get My Location’, program progress about 5 minutes, after textview was null. My phone is HTC hero, if i try with emulator, result is ok.
    Thank you very much.

  4. I tested outdoors yesterday, result wasn’t ok. I turned on GPS: Settings -> location &security -> use GPS satellites (checked).
    Network provider: Settings -> wireless & network settings -> mobile network -> data enabled(checked).
    can you see my wrong?
    Thanks!

  5. About Network Location provider.
    You wrote: “Network provider: Settings -> wireless & network settings -> mobile network -> data enabled(checked).”

    You enabled access to internet via your mobile operator.

    Please make checkbox checked in Settings -> Location -> Use wireless networks. It is settings in my HTC Desire. I don’t know what name of this setting in your HTC Hero. This setting means that you can use a-GPS.

  6. Hi!

    Your tutorial is very useful, but it doesn’t work for mee!
    I am using emulator 2.1 can it be a problem?

    Thanks,
    Peter

  7. hi Igor
    when i used your program. i saw in logcat:
    09-21 04:34:21.004: DEBUG/libloc(189): Event RPC_LOC_EVENT_PARSED_POSITION_REPORT (client 0)
    09-21 04:34:21.004: DEBUG/libloc(189): Session status: RPC_LOC_SESS_STATUS_IN_PROGESS Valid mask: 0x606D
    09-21 04:34:21.004: DEBUG/libloc(189): Latitude: 15.8900017 (intermediate)
    09-21 04:34:21.004: DEBUG/libloc(189): Longitude: 105.8000028
    09-21 04:34:21.004: DEBUG/libloc(189): Accuracy: 0.0000000
    09-21 04:34:21.364: DEBUG/libloc(189): Event RPC_LOC_EVENT_SATELLITE_REPORT (client 0)
    09-21 04:34:21.364: DEBUG/libloc(189): sv count: 0
    but in textview: “My Location is”: process (not display longitude and latitude)..
    Can you help me get infomation in log?

  8. Hi, thanks for this example..
    I got latitude and longitude datas correctly.. Bu t I have a problem. I would like to get also speed (car speed). For this aim, I used :
    ” String speed = “Speed: ” + location.getSpeed(); ” And, I tested program with my telephone in the car that in motion. Hovewer, I got speed values like 1.39466, 1.69499 or 0. I don’t understand this problem reason.

    I hope, you will help me..

  9. I get an error here

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);

    progress = (ProgressBar) findViewById(R.id.progressBar1);
    progress.setVisibility(View.GONE);

    buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
    buttonGetLocation.setOnClickListener(this);

    locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    It says id can’t be resolved or is not a field.What to do?

  10. Hi, this tutorial is very useful.
    I have a question.
    If my device enable GPS and network then :
    – duplicate call get location ?
    – get location will run slowly ?

  11. hi..thx for your psot if very helpfull. btw i try to adding the geocode into your code for get a adress form the lat and long with a litle modification, but i got an force close.. can you help me

  12. Hi

    Why are we sending mock location data ? Is this code get direction when i push the “Get My Direction” ?

  13. Hi, simran
    You can create table with two columns “lat” and “lng”. Then you can put coordinates into these columns as TEXT data.

  14. I am using this tutorial for finding GPS locaton and my code is as same as above but i am not geting location. only this message ” Sorry, location is not determined” is displayed. Please help me.

Leave a Reply

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


two + = 10

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">