-3

I am creating a tracking android application and I am using Fused locaiton api for get location but same return wrong location sometime.

Please help to get accurate lat lang everytime.

below code i am using for get lat lang. Code is working firm but sometime it gave worng location. But when i open google map in my device than location again return correct.

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        currentLatitude = mLastLocation.getLatitude();
        currentLongitude = mLastLocation.getLongitude();

        currentLocation = new Location("");
        currentLocation.setLatitude(currentLatitude);
        currentLocation.setLongitude(currentLongitude);

        distanceInMeters = addressLocation.distanceTo(currentLocation);

        tvDistance.setText(String.valueOf(distanceInMeters) + " Mtr");

        if (distanceInMeters > GPS_RADIUS) {
            distanceStatus = "Not Matched";
            tvMatchStatus.setText(R.string.not_match);
            layout.setBackgroundColor(Color.parseColor("#FFFF0900"));
        } else {
            distanceStatus = "Matched";
            tvMatchStatus.setText(R.string.matched);
            layout.setBackgroundColor(Color.parseColor("#FF2CFD03"));
        }

        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        hideProgressDialogLocationMatch();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                try {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        // permission was granted. Do the
                        // contacts-related task you need to do.
                        if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {

                            if (mGoogleApiClient == null) {
                                buildGoogleApiClient();
                            }
                        }

                    } else {

                        // Permission denied, Disable the functionality that depends on this permission.
                        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        try {
//            closeAllActivity(this);
            startLocationUpdates();
            if (alert.isShowing()) {
                alert.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

1 Answers1

0

use this code and replace mFusedLocationClient with your FusedLocationProviderClient's object

mFusedLocationClient.getLastLocation()
        .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location == null) {
                    Log.w(TAG, "onSuccess:null");
                    return;
                }

                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        2000,
                        10, new LocationListener() {
                            double latitude;
                            double longitude;

                            @Override
                            public void onLocationChanged(Location location) {
                                try {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();

                                    String msg = "New Latitude: " + latitude + "New Longitude: " + longitude;
                                    Log.d("Message", msg);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.d("Error", "Bad Network Connection");
                                    latitude = mLastLocation.getLatitude();
                                    longitude = mLastLocation.getLongitude();
                                }
                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {
                            }

                            @Override
                            public void onProviderEnabled(String provider) {
                            }

                            @Override
                            public void onProviderDisabled(String provider) {
                            }
                        });

            }
        })
        .addOnFailureListener(getActivity(), new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "getLastLocation:onFailure", e);
            }
        });
Nirmal Prajapat
  • 1,735
  • 1
  • 12
  • 23