javaandroidgoogle-mapsfusedlocationproviderclient

How to use getCurrentLocation of fused location provider client?


I am new for Android coding, and have writen a code to get location of Android Device but failed. Nothing changed (e.g. mLastKnownLocation or cityName) after runing, and no expception. I have already checked permission and build.gradle. Could you give me advices to implement it?

private void getDeviceLocation() {
        try {
            if (mLocationPermissionGranted) {

                Task<Location> locationResult = mFusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,cancellationToken);
                //Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();

                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>(){
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Obtain the current location of the device
                            mLastKnownLocation = task.getResult();
                            String currentOrDefault = "Current";

                            if (mLastKnownLocation != null) {
                                Log.d(TAG, "Get current location");
                            } else {
                                Log.d(TAG, "Current location is null. Using defaults.");
                                currentOrDefault = "Default";

                                // Set current location to the default location
                                mLastKnownLocation = new Location("");
                                mLastKnownLocation.setLatitude(mDefaultLocation.latitude);
                                mLastKnownLocation.setLongitude(mDefaultLocation.longitude);
                            }

                            String city = "CorrectCity";
                            try {
                                List<Address> address =
                                        geocoder.getFromLocation(mLastKnownLocation.getLatitude(),
                                        mLastKnownLocation.getLongitude(), 1);
                                if(address.isEmpty())
                                    city = "No_city";
                                else{
                                Address target = address.get(0);

                                if(target.getLocality()!=null)
                                    city = target.getLocality();
                                else
                                    city = target.getAdminArea();}
                            } catch (IOException e) {
                                Log.e("Exception: %s", e.getMessage());
                            }

                            cityName = city;
                            // Show location details on the location TextView
                            String msg = currentOrDefault + " Location: " +
                                    Double.toString(mLastKnownLocation.getLatitude()) + ", " +
                                    Double.toString(mLastKnownLocation.getLongitude())+ "  " +
                                    cityName;
                            locationTextView.setText(msg);

                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            /*mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);*/
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
            cityName = "ErrorCity";
        }
    }
}

Solution

  • You can get your last known location using the code below

    FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
    fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
        if (location != null) {
            // your last known location is stored in `location`
        }
    });
    

    refer: https://developer.android.com/training/location/retrieve-current


    Using Location Manager

    LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    LocationListener listener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            mMap.clear();
            LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.addMarker(new MarkerOptions().position(userLocation).title("Me"));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
        }
    
        @Override
        public void onProviderEnabled(@NonNull String provider) {
    
        }
    
        @Override
        public void onProviderDisabled(@NonNull String provider) {
    
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    };
    
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);