javaandroidlocation-services

getLastKnownLocation first time return null issue


I'm developing a simple android location app but I have a little bit trauble.(Also sorry for my bad english.)

I want to get current location with button click, but getLastKnownLocation returns null all of first time.

But also if I first opened google maps and show my current location on map, after that I passed background it then I opened my own app, click the button that works. But I dont want this way, I just want provide location on the my app not with this way.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Object clipboardService = getSystemService(CLIPBOARD_SERVICE);
    final ClipboardManager clipboardManager = (ClipboardManager) clipboardService;
    tvEnlem = (TextView) findViewById(R.id.textViewEnlem);
    tvBoylam = (TextView) findViewById(R.id.textViewBoylam);
    retrieveLocationButton = (Button) findViewById(R.id.buttonNeredeyim);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }


    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        return;
    }


    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();

        this.tvBoylam.setText(String.valueOf(location.getLongitude()));
        this.tvEnlem.setText(String.valueOf(location.getLatitude()));

    }
    else{

        Toast.makeText(MainActivity.this,"LOKASYON BİLGİLERİ BOŞ",
                Toast.LENGTH_SHORT).show();

    }


}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}



}

How can I get location without null values?


Solution

  • this isn't a bug but simply the Google politics. The getLastKnowLocation() method return the last location that google service has retrieved. As Google Documentation says:

    The location object may be null in the following situations:

    • Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because
      disabling location also clears the cache.
    • The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
    • Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted.

    This is why if you switch from Google Maps to your app, you can get last location. To get actual position without pass from an app to other, you need to implement a new client and request location updates yourself. For more information, see Receiving Location Updates.

    I hope I have clarified your every doubt. Otherwise, do not hesitate to write :)