[Android] Get your GPS Coordinates

Before getting into this tutorial, you need to know how an android application code works and how different important file interact with each other (To be updated)

1. Insert the following code into your Manifest.xml to enable accessing location services:

<!-- Adding for accessing location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />

2. Add the following code to onCreate() in your Activity.java


// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new myLocationListener();

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0 , locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0 , locationListener);

3. Lastly, create a private class inside your Activity class


private class myLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {


if(location != null) {
Toast.makeText(LocationService.this,
location.getLatitude() + "\n" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
else {
}
}

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

@Override
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();

}

@Override
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(),"Gps Enabled", Toast.LENGTH_SHORT ).show();
}
}

 

There you go! Try the code now!