Create location manager and location listener instance and bind them after checking permissions are granted
AndroidManifest.xml
<!--permission to get location--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
We dont need explicit permission check
public class MainActivity extends AppCompatActivity {
// create location manager and location listener instance
LocationManager locationManager;
LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Have this code under mapReady method when using map activity
Log.i("Creating", "Creating something");
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i("Location",location.toString());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
if(Build.VERSION.SDK_INT < 23){
//Bind the location manager with location listener
// updates in time interval 0 and on distance change of more than 10 meter
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
}
We have to add explicit permission checks and find out if they are granted or rejected
@Override
protected void onCreate(Bundle savedInstanceState) {
...
...
if(Build.VERSION.SDK_INT < 23){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
}else{
//Ask for permission if it is not granted in the context
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1); //last param is tag, which can be used to match request call
}else{
//sometimes the permission states are saved in the device and it wont ask again.
Log.i("Permitted ","Permitted already");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
}
}
}
//This method will be called after permission allow dialog has been responded
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//Check if permission id granted or not granted
Log.i("Info ","Asking for permission");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
//bind location manager and listener if permission is granted
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
}
}
}
Getting the address form the coordinates
Inside Locationlistener
@Override
public void onLocationChanged(Location location) {
Log.i("Location ",location.toString());
// Add a marker to current location
LatLng deviceLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();//remove previous markers
mMap.addMarker(new MarkerOptions().position(deviceLocation).title("Device location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(deviceLocation));
//Geocoding
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
try {
//get address corresponding to coords. Limit max address to 1.
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
if(listAddresses != null && listAddresses.size() > 0){
Log.i("Place info ", listAddresses.get(0).toString());
//make the address look ordered (optional)
String addressStr = "";
if(listAddresses.get(0).getSubThoroughfare() != null)
addressStr += listAddresses.get(0).getSubThoroughfare() + " ";
if(listAddresses.get(0).getThoroughfare() != null)
addressStr += listAddresses.get(0).getThoroughfare() + ",";
if(listAddresses.get(0).getLocality() != null)
addressStr += listAddresses.get(0).getLocality() + ", ";
if(listAddresses.get(0).getPostalCode() != null)
addressStr += listAddresses.get(0).getPostalCode() + ", ";
if(listAddresses.get(0).getCountryName() != null)
addressStr += listAddresses.get(0).getCountryName();
Toast.makeText(MapsActivity.this,addressStr,Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}