, ,

Android Get Current Location from GPS or Internet/Data

August 9, 2014

Android has a feature of getting your current location by running the device’s Global Positioning System (GPS) or connecting to your wifi or network provider’s data.


1. We need to use the getSystemService method from Activity object to get the Location Service and cast it as Location Manager.

public class MyActivity extends Activity{

protected void onCreate(Bundle b){


android.location.LocationManager lm = (android.location.LocationManager) getSystemService (android.content.Context.LOCATION_SERVICE);


if not within Activity class, we can access it through Context object. In your activity class pass “this” object to the method you’re calling.

public class MyActivity extends Activity{

protected void onCreate(Bundle b){


MyClass myClass = new MyClass();


// Method from another class
public void getLocation(Context context){

android.location.LocationManager lm = (android.location.LocationManager) context.getSystemService (android.content.Context.LOCATION_SERVICE);



2. Now we have the object Location Manager, we must request for location updates first by calling a method from Location Manager.


notice we have four parameters. Below are from Android API

provider the name of the provider with which to register
minTime minimum time interval between location updates, in milliseconds
minDistance minimum distance between location updates, in meters
listener LocationListener whose onLocationChanged(Location) method will be called for each location update

example :

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,1, locationListener);


I found a very good site to learn about the LocationListener.

3. Finally, we can get the Location object.

location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

Add this in your manifest.

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



Have your say