0

I am develop a app in Android. I use Location and Location manager to get a current position, but if i turn off and turn on the GPS on app execution, location.getLastKnownLocation return null. This is the code.

@Override
public void onClick(View view) {
    if(!checkGPSEnabled()){
        dialogCheckGPS();
    }else{
        Intent i =new Intent(getApplicationContext(), ZoneUser.class);
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location==null)
            Toasty.success(getApplicationContext(),"Es null").show();
        Bundle bundle = new Bundle();
        bundle.putDouble("lat",location.getLatitude());
        bundle.putDouble("lng",location.getLongitude());
        i.putExtras(bundle);
        startActivity(i);
    }
}

I use Intent and Bundle to get latitude and longitude to another activity, but location return null.

Thanks.

vahdet
  • 6,357
  • 9
  • 51
  • 106
Mario
  • 23
  • 5
  • 1
    as per the docs, cached location is flushed when the user turns the location provider off. so you will get null after that for some time even when user turns the location back on as it takes some time to acquire location from network/tower/gps. you need to listen for user turning off location provider and ask them to turn it back on and "listen" for updates using a service til you receive a location- or just tell them to keep smashing refresh until they get a location. – Karan Harsh Wardhan Mar 29 '19 at 12:18
  • please prefer [Google Location API](https://stackoverflow.com/a/33291227/6880611) for getting lat long – Tejas Pandya Mar 29 '19 at 12:19
  • The `getLastKnownLocation()` doesn't trigger any operarion to update the device's location. It only returns a value if the location happens to be known. If you really want an up-to-date location, you need to request location updates. – Markus Kauppinen Mar 29 '19 at 12:34

0 Answers0