FusedLocationApi有时不提供正确的位置

时间:2018-01-12 06:27:23

标签: android android-fusedlocation

我正在开发一个高度依赖于用户位置和地理围栏的应用程序。我试图首先获得用户位置,并基于进一步的操作。一切都工作得很好,除了有些时候我得到错误的位置值,除非我重新启动应用程序,在某些情况下,重新启动手机,我没有得到正确的值。我将在下面发布我的位置Api代码。如果需要更改,请告诉我。

       manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    buildGoogleApiClient();
    if (!statusOfGPS) {
        displayPromptForEnablingGPS(this);

    } else {
        permissionAndLocationAccess();
    }
 @Override
public void onConnected(@Nullable Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update location every second
    if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    } else {
        ProgressUtil.hideProgressDialog(prgd_progressDialog);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = mLastLocation.getLatitude();
            lon = mLastLocation.getLongitude();
            Log.e("Lat and Lng", "onconn");
            if (!String.valueOf(lat).equals("0.0")) {
                latitudeVal = mLastLocation.getLatitude();
                longitudeVal = mLastLocation.getLongitude();
                sendLatLong(latitudeVal, longitudeVal);
                Log.d("Lat and Lng", "in last loc");
                Log.d("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
                new AsyncCaller().execute();

            }
        }
    }
}
 @Override
public void onLocationChanged(Location location) {
    if (location != null) {
        lat = location.getLatitude();
        lon = location.getLongitude();
        Log.e("Lat and Lng", "onchanged");
        if (!String.valueOf(lat).equals("0.0")) {
            latitudeVal = location.getLatitude();
            longitudeVal = location.getLongitude();
            ProgressUtil.hideProgressDialog(prgd_progressDialog);
            Log.e("Lat and Lng", "onchanged0");
            Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);

1 个答案:

答案 0 :(得分:0)

我也在使用这个课程,在我的情况下,它的工作正常。你可以检查

public class BackgroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

protected static final String TAG = "BackService";

public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = GLOBAL_BACKGROUND_CHECK_TIME;
public GoogleApiClient mGoogleApiClient;
public LocationRequest mLocationRequest;
private PendingIntent mPendingIntent;
IBinder mBinder = new LocalBinder();

private class LocalBinder extends Binder {
    public BackgroundLocationService getServerInstance() {
        return BackgroundLocationService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "onCreate()");

    Intent mIntentService = new Intent(this, LocationUpdates.class);
    mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
    buildGoogleApiClient();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG + " onStartCmd", "Connected");
        return START_STICKY;
    }

    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
        Log.i(TAG + " onStartCmd", "GoogleApiClient not Connected");
        mGoogleApiClient.connect();
    }
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this);

    notification.setContentTitle("Title ");
    notification.setContentText("\n Tracking BackGround ... ");
    notification.setSmallIcon(R.drawable.big_marker);
    notificationManager.notify(151458461, notification.build());


    return START_STICKY;
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
    createLocationRequest();
}

protected void createLocationRequest() {
    Log.i(TAG, "createLocationRequest()");
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(GLOBAL_BACKGROUND_CHECK_TIME);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


}

protected void startLocationUpdates() {
    Log.i(TAG, "Started Location Updates");
    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, mPendingIntent);
}

public void stopLocationUpdates() {
    Log.i(TAG, "Stopped Location Updates");
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    startLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {

    String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() +
            "\n location Accuracy: " + location.getAccuracy() + "\n speed: " + location.getSpeed();
    Log.d(TAG, "onLocationChanged: " + message);
}

@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "Connection suspended");
    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();

}

}