如何获得准确的GPS位置在Android中使用谷歌API(融合位置)?

时间:2016-01-07 14:25:01

标签: android gps location

我正在使用Google APIGPS中的Android获取位置信息。如果我搬家,我会得到准确的位置。但如果我在15 mins之上的同一位置,它会提供更多位置。

我的代码是:

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);
    }



}

请帮帮我。提前谢谢.....

我评论了这个链接http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/

请帮我解决这个问题....

如果我在同一个地方,我会得到这个位置  enter image description here

1 个答案:

答案 0 :(得分:0)

前几天我遇到了同样的问题。我已将setPriority()更改为PRIORITY_BALANCED_POWER_ACCURACY。它可能会解决您的问题。

您在PRIORITY_HIGH_ACCURACY方法中使用了createLocationRequest()

取代此行 mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

添加此行 mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

发生此问题是因为使用onLocationChanged调用的PRIORITY_HIGH_ACCURACY方法,它为我们提供了不同的新位置

  

我的建议是使用PRIORITY_BALANCED_POWER_ACCURACY