所以,我有一个在背景上称为的工作服务。但是,我需要它来获取当前位置并将其发送到Web服务。当我发送静态数据时,Web服务的运作良好。但是,获得位置是一个问题。位置对象始终为空。这就是我一直在尝试的。
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如果没有位置修复,则返回null,这意味着除非您在其他地方使用GPS,否则它几乎总是返回null。为了确保您获得位置使用getLocationupdates并等待位置修复(这不会瞬间,具体取决于大气条件,无论您是内部还是外面等只是永远不会发生)。
显然代码很好,要使它起作用,这就是我所做的:
- 检查应用程序的权限(需要激活一个位置)
- 将您的GPS设置更改为(移动数据和WiFi One)
用当前的代码发布了此问题。