0

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());
}
sininen
  • 503
  • 1
  • 6
  • 20
  • 1
    First of all you cannot update user location every second .. it is done by onLocationChanged() whenever location is changed. Are you looking to ask permission from user on every location change ? – FaisalAhmed Aug 14 '17 at 13:07
  • I was following a tutorial which was doing it this way. – sininen Aug 14 '17 at 13:08
  • @Pavneet_Singh this does not work either – sininen Aug 14 '17 at 13:09
  • 2
    From user experience point of view. It is not good idea to ask permission of each location change. Please be clear what u want to achieve – FaisalAhmed Aug 14 '17 at 13:10
  • I have to ask the user for permission, when I do not Android Studio says I have to check if permission is available (with checkPermission) – sininen Aug 14 '17 at 13:37
  • It is done only one time when user install app and if user gives permission to that app to access his location then it does not ask permission again. However you can go in setting and remove permission whenever you want. – FaisalAhmed Aug 14 '17 at 13:46

0 Answers0