If users gives permission, a background service is created that starts tracking user locations.
Background service keeps tracking user location,even after user destroys the application.
But if user goes to application settings and remove location permission then service crashes and gives following error message,
java.lang.SecurityException: Client must have ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to perform any location operations.
The service runs after every 10 seconds, Kindly guide me how to check this in running service, that either it has permissions or not, because after every 10 seconds it runs the service and calls onLocationChanged
method.
public class UpdateService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
@Override
public void onCreate() {
super.onCreate();
if (isGooglePlayServicesAvailable()) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
super.onStartCommand(intent, flags, startId);
return START_STICKY ;
}
@Override
public void onLocationChanged(Location location) {
saveLocationand(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
EDIT:
This is how i check permission in Application launch
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showGPSDisabledAlertToUser();
}
startService(new Intent(MainActivity.this, UpdateService.class));
} else
checkLocationPermission();
}