0

LocationManager is always returning false in oreo and above devices when i check if gps is on or not, even when i turn it on, it still returns false. How do i check if gps is on in oreo and and above devices?

Heres my code:

Location manager;

  manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

           //this if check is always false even when gps is on    
 startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }


void onRestart(){
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

         //still returning false when i come back to app from settings screen after turning on gps, but it returns true in android Nougat devices perfectly
            }
}
Maximus
  • 189
  • 1
  • 3
  • 15

2 Answers2

1

Please use the fused location client
Documentation
It's battery efficient and very easy to work with and is pretty much the standard in location based apps.
A youtube tutorial

An example from one of my apps:

@Override
public void onStart() {
    super.onStart();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
}

@Override
public void onMapReady(GoogleMap googleMap) {
    if (googleMap == null) return;// GUARD
    map = googleMap;
    getDeviceLocationUpdates();
}  



/**
 * Start listening to location changes
 */
private void getDeviceLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationRequest = new LocationRequest();

    locationRequest.setInterval(Constants.DRIVING_TIME_INTERVAL);
    locationRequest.setFastestInterval(Constants.DRIVING_TIME_INTERVAL);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

}  



LocationCallback locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        List<Location> locationList = locationResult.getLocations();
        if (locationList.size() > 0) {
            //The last location in the list is the newest
            Location location = locationList.get(locationList.size() - 1);
            Log.i(TAG, "Location: " + location.getLatitude() + " " + location.getLongitude());
            lastLocation = location;

            if (currentLocationMarker != null) {
                currentLocationMarker.remove();
            }

            if (mapPin == null) {
                mapPin = GraphicUtils.resizeImage(getActivity(), Constants.MAP_MARKER_IMAGE_NAME, 100, 100);
            }

            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            placeCurrentLocationMarker(latLng);

            //move map camera
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, Constants.DEFAULT_ZOOM));
        }
    }
};  



/**
 * Places a marker with user image on the map on given location
 *
 * @param location GPS Location
 */
private void placeCurrentLocationMarker(LatLng location) {
    Bitmap bitmap = GraphicUtils.createContactBitmap(getActivity(), BitmapFactory.decodeResource(
            getActivity().getResources(),
            Integer.valueOf(((MainActivity) getActivity()).currentUser.getImgUrl())));
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(location);
    markerOptions.title(getString(R.string.you_are_here));
    markerOptions.icon((bitmap == null) ?
            BitmapDescriptorFactory.fromBitmap(mapPin) :
            BitmapDescriptorFactory.fromBitmap(bitmap));
    currentLocationMarker = map.addMarker(markerOptions);
}
Mark Kazakov
  • 946
  • 12
  • 17
  • Tried already, and tried to get last known location also, i got few times when my gps was already on,other times, got null, that is what my question is, how do i check if gps is on or not in oreo and above devices. – Maximus Jan 21 '19 at 07:22
  • Check gps is correctly working on ur device.Check with google map app. – SIVAKUMAR.J Jan 21 '19 at 07:47
  • I've edited the answer and added an example from a production app which works great. – Mark Kazakov Jan 21 '19 at 08:34
  • @MarkKazakov i have used this fusedLocationProvider long ago already, you are not understanding the problem, the problem is i need to turn on users gps automatically or atleast check if its on or not , have you tried using your code with gps off? try that and let me know. Your code wont be able to get location if gps is off. I think you are running your app with gps on already, which can be a flaw. – Maximus Jan 21 '19 at 08:56
  • @Maximus I'm checking the GPS before. You can see how to to that here - https://stackoverflow.com/questions/44024009/how-to-check-if-gps-i-turned-on-or-not-programmatically-in-android-version-4-4-a?answertab=votes#tab-top – Mark Kazakov Jan 21 '19 at 09:15
  • The GPS doesnt has to be on because the GPS location can be fetched using your cecular provider, it is less accurate but fused location utilizes that option too, that's why even without the GPS function on location can still be fetched. – Mark Kazakov Jan 21 '19 at 09:16
  • my locationCallback is not getting called i dont know why – Maximus Jan 21 '19 at 10:05
  • Also when i am turning on gps and then starting the app, its showing lat long and locationCallback is being called even though i have kept locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); – Maximus Jan 21 '19 at 10:16
  • Do you have ACCESS_COARSE_LOCATION in the manifest? Perhaps checking if GPS is on is the way to go as you suggested – Mark Kazakov Jan 21 '19 at 10:57
0

There is another possibility that is not really related to the device being Oreo or not, but in the settings activity you redirect via startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); you may not enabled the GPS provider itself. Also since you said Oreo and above I think you have already given the permission of android.manifest.Permission.ACCESS_FINE_LOCATION both in runtime and in manifest.

If you noticed, there are 3 providers: GPS_PROVIDER, NETWORK_PROVIDER and PASSIVE_PROVIDER. You are using GPS_PROVIDER to fetch your location, but if it is not enabled via the settings, it might return false. Only network provider might have been selected while you're trying this.

Here is a picture of what I'm talking about (from HUAWEI-P20 Lite - Android 8.0.0 API 26):

Click if not visible

Furkan Yurdakul
  • 2,801
  • 1
  • 15
  • 37