简体   繁体   中英

How to get accurate GPS location Using google API(Fused Location) in android?

I am using Google API to get location from GPS in Android . i got accurate location if i moving. but if i am in same location above 15 mins it give more locations.

My code is:

public class LocationServiceTesting extends Service
        implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener {  

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation,mLastLocation,Test3LastLocation,Test2LastLocation;
    String mLastUpdateTime;


    String DeviceCode = "", ImeiNumber = "";

    protected void createLocationRequest() {        
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private boolean isGooglePlayServicesAvailable(Context context) {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, (Activity) context, 0).show();
            return false;
        }
    }

    public LocationServiceTesting() {
        // TODO Auto-generated constructor stub
    }



    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        Log.d(TAG, "onCreate ...............................");
        // show error dialog if GoolglePlayServices not available
        Log.d(TAG, "on play service "+checkPlayServices());
        if (checkPlayServices()) {

            Log.e("oogleplay service found", "service");
            buildGoogleApiClient();
            createLocationRequest();
        }


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        super.onStartCommand(intent, flags, startId);
        if(!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
        return START_STICKY;

    }
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
         if (mGoogleApiClient != null) {
                mGoogleApiClient.connect();
            }
    }



    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if(mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // TODO Auto-generated method stub
        Log.d(TAG, "Connection failed: in service " + connectionResult.toString());

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        Log.e(TAG, "onConnected - isConnected inservice " + mGoogleApiClient.isConnected());
        startLocationUpdates1();

    }

    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
        Log.d(TAG, "Location update started ..............: ");

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub
        mGoogleApiClient.connect();

    }

    // get distance between two latlong
    public double getDistance(Location Lastlocation, Location Currentlocation) {
        double distance = 0;
        distance = Lastlocation.distanceTo(Currentlocation);
        return distance;

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub


        Sync synctoServer = new Sync();
        Log.e("With out API Location ", "location  "+location);

                if (location.getAccuracy() < 20) {
                    Location Curloc;
                    double Distance=0.0;
                    Curloc= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    if(Test3LastLocation!=null)
                    {
                        Distance=getDistance(Test3LastLocation, Curloc);
                        Log.e("Distance", "Distance "+Distance);
                    }

                    if(Distance>20)
                    {
                        dbo.InsertGPS(dbo, DeviceCode, ImeiNumber, "" + location.getLongitude(), "" + location.getLatitude(),
                                _contrl.getCurrentTimeStamp());

                    }


                Test3LastLocation=Curloc;
                }


        mLastLocation = location;

        displayLocation();


    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }


    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                //GooglePlayServicesUtil.getErrorDialog(resultCode, this,PLAY_SERVICES_RESOLUTION_REQUEST).show();
                Toast.makeText(getBaseContext(), "play service not", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                //finish();
            }
            return false;
        }
        return true;
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            //lblLocation.setText(latitude + ", " + longitude);
            Log.e("Location chnage ", ""+mLastLocation+" "+mLastLocation.getTime()+" "+mLastLocation.getElapsedRealtimeNanos());

        } else {
            Log.e("Location chnage ", "null values");

            //lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }


    protected void startLocationUpdates1() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }



}

please help me. thanks in advance.....

I refereed this link http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/

please help me to over come this problem....

I am getting this like location if i am in a same location 在此处输入图片说明

I had same issue before few days ago.I have changed the setPriority() to PRIORITY_BALANCED_POWER_ACCURACY . It might resolve your problem.

You have used PRIORITY_HIGH_ACCURACY in your createLocationRequest() method.

Instead of this line mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

Add this line mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

This issue is occurred because of onLocationChanged method called with PRIORITY_HIGH_ACCURACY and It gives us new location which is different .

My suggestion is to use PRIORITY_BALANCED_POWER_ACCURACY .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM