FusedLocationApi 有时无法提供正确的位置

Posted

技术标签:

【中文标题】FusedLocationApi 有时无法提供正确的位置【英文标题】:FusedLocationApi not providing the proper location sometimes 【发布时间】:2018-06-21 14:07:34 【问题描述】:

我正在开发一个高度依赖用户位置和地理围栏的应用程序。我试图首先获取用户位置,并在此基础上进行进一步的操作。一切正常,除了以下事实,有时我得到错误的位置值,除非并且直到我重新启动应用程序并且在某些情况下重新启动手机,否则我没有得到正确的值。我将在下面发布我的 Location 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】:

我也在使用这个类,就我而言,它工作正常。你可以检查

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


【讨论】:

谢谢。让我检查一次

以上是关于FusedLocationApi 有时无法提供正确的位置的主要内容,如果未能解决你的问题,请参考以下文章

CSS 有时在初始加载时无法正确加载

UITableView“有时”无法正确绘制单元格

UICollectionViewCell 中的 UILabel 有时无法正确调整大小

Visual Studio 2022 有时会显示“应用程序无法正确启动”

IE7(有时)无法正确显示网站

setMockMode 不起作用 - FusedLocationApi