服务作为位置变得空

Service getting null as location

所以,我有一个正在后台调用的 JobService。但是我需要它来获取当前位置并将其发送到网络服务。当我发送静态数据时,网络服务运行良好。但是获取位置是一个问题。位置对象始终为空。这就是我一直在尝试的。

public class GPSBackgroundJobService extends JobService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private String LOGSERVICE = "GPS";

private InspectorsLogic mInspectorsLogic;
ParsoContext mContext;

private GoogleApiClient mGoogleApiClient;

ParsoLocationListener mLocationListener;
Location mLastLocation;
Double longitude;
Double latitude;



@Override
public void onCreate() {
    super.onCreate();
    Log.i(LOGSERVICE, "onCreate");
    mContext = (ParsoContext) getApplicationContext();
    mInspectorsLogic = new InspectorsLogic(mContext);


    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}





@Override
public boolean onStartJob(JobParameters job) {
    Log.i(LOGSERVICE, "onStartJob called");
    mGoogleApiClient.connect();
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLastLocation!=null) {
        latitude = mLastLocation.getLatitude();
        longitude =mLastLocation.getLongitude();
        sendGPSTask mSendGPSTask = new sendGPSTask();
        mSendGPSTask.execute(Double.toString(latitude), Double.toString(longitude));
    }else{
        Log.e(LOGSERVICE, "Lat and Long are null");
    }
    return false;
}

@Override
public boolean onStopJob(JobParameters job) {
    mGoogleApiClient.disconnect();
    return false;
}

@Override
public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}


}

getLastLocation returns null 如果它还没有位置修复 - 这意味着除非您在其他地方使用 GPS,否则它几乎总是 returns null。为确保您获得位置,请使用 getLocationUpdates 并等待位置修复(这不会是即时的,具体取决于大气条件,无论您是在室内还是室外等,这可能需要几秒钟到一分钟左右 - 或者永远不会发生)。

显然代码没问题,我就是这样做的:

  1. 查看应用权限(需要激活的位置)
  2. 将您的 GPS 设置更改为(移动数据和 wifi 之一)

用问题上发布的当前代码制作这个,成功了。