I have an Android application that sends GPS location to a DB.
I tested it today and found that the location manager needs permission to call requestLocationUpdates
.
I want to set permission on allowed and I don't want to ask the device or the user for permission.
Now, the code requires to add some code to ask for permission?
/**
* Enable location services
*/
public void connect() {
Log.d(TAG, ".connect() entered");
// Check if location provider is enabled
String locationProvider = LocationManager.NETWORK_PROVIDER;
if (!locationManager.isProviderEnabled(locationProvider)) {
Log.d(TAG, "Location provider not enabled.");
app.setCurrentLocation(null);
return;
}
// register for location updates, if location provider and permission are available
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
locationManager.requestLocationUpdates(bestProvider, Constants.LOCATION_MIN_TIME, Constants.LOCATION_MIN_DISTANCE, this);
app.setCurrentLocation(locationManager.getLastKnownLocation(locationProvider));
}
}
/**
* Disable location services
*/
public void disconnect() {
Log.d(TAG, ".disconnect() entered");
String locationProvider = LocationManager.NETWORK_PROVIDER;
if (locationManager.isProviderEnabled(locationProvider)) {
locationManager.removeUpdates(this);
}
}
I have added to manifest too. PS: This permission is newly required because I have been testing the app days ago on the same device ( Android 4.4) and it worked well. Is it possible that some default permission on Android has changed since 2017/08/21? If so how can I change it?
You will have to write a method to check whether permission is given by user. If not then ask user for permission. Constants.LOCATION_PERMISSION_REQUEST is just requestcode to match when got callback in onRequestpermission result
public static boolean checkLocationPermission(Activity activity){
if(ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.LOCATION_PERMISSION_REQUEST);
return false;
}
return true;
}
As the user allows, you will get callback on overridden method "onRequestPermissionsResult()"