I am trying to update the users location every second (every second I want a log message to appear which contains the actual position of the user), for this I have to ask the user at run time if he wants to allow the app to get access to his position only once (I have to ask because API 24 requires this). After the user has accepted the app does not ask again.
But onLocationChanged
does not get called.
@Override
protected void onCreate(Bundle bundle) {
//initializing UI
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
mLocationRequest.setInterval(1000);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
return;
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == 1) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
@Override
public void onLocationChanged(Location location) {
Log.i("LOCATION", location.toString());
}