, ,

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){

super.onCreate(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){

super.onCreate(b);

MyClass myClass = new MyClass();

myClass.getLocation(this);

}
// 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.

locationManager.requestLocationUpdates(1,2,3,4);

notice we have four parameters. Below are from Android API

Parameters
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);

Providers are NETWORK_PROVIDER and GPS_PROVIDER.

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);

or

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