2017-02-21 50 views
0

所以,我有一個在後臺調用的JobService。不過,我需要它來獲取當前位置並將其發送到Web服務。當我發送靜態數據時,web服務運行良好。然而,獲取位置是一個問題。位置對象始終爲空。這是我一直在嘗試的。如果它不具有位置鎖定的yet-這意味着,除非你使用GPS的其他地方,它幾乎總是返回null服務變得空作爲位置

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) { 

} 


} 

回答

0

顯然,代碼是好的,使它工作,這是我做過什麼:

  1. 檢查應用程序的權限
  2. 改變您的GPS設置(一個需要被激活的位置)(移動數據和wifi一個)

使這與當前代碼張貼在問題上,做了它。

0

getLastLocation返回null。爲了確保獲得位置,請使用getLocationUpdates並等待位置修復(這不會是即時的,取決於大氣條件,無論您是在裏面還是外面等等,這可能需要幾秒鐘到幾分鐘左右的時間,或者只是永遠不會發生)。