1

I'm developing an app and when I try to get the location of Android, I always get null.

I try this with a real device, running API 19 and with the GPS enabled

This is my code:

double latitud, longitud;    
Location location;
LocationManager mlocManager;
LocationListener locationListener;
String provider;

    final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!gpsEnabled) {
        Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(settingsIntent);
    }
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
        return;
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    provider = mlocManager.getBestProvider(criteria, true);
    Log.i("PROVIDER", provider);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitud = location.getLatitude();
            longitud = location.getLongitude();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {


        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };
    mlocManager.requestLocationUpdates(provider, 0, 0,locationListener);
    location = mlocManager.getLastKnownLocation(provider);
    if (location != null) {            
        latitud = location.getLatitude();
        longitud = location.getLongitude();
        Log.i("LATITUD GPS", String.valueOf(latitud));
        Log.i("LONGITUD GPS", String.valueOf(longitud));


    } else {
        Log.e("LOCATION", "null");            
    }
}

I tried to use LocationManager.GPS_PROVIDER instead of Criteria, but it doesn't work.

Thanks in advance.

K.Os
  • 5,123
  • 8
  • 40
  • 95
David
  • 73
  • 5
  • 2
    https://stackoverflow.com/a/21586537/115145 https://stackoverflow.com/a/43396965/115145 https://stackoverflow.com/a/34078768/115145 – CommonsWare Jul 23 '17 at 15:32

0 Answers0