2016-11-11 26 views
0

我是Android新手我想在後臺運行一個服務,並在10分鐘後獲取經緯度或地理位置地址併發送到服務器。從後臺服務沒有獲取經緯度

請幫幫我。

這裏是我的代碼:

在活動

public void serviceCall(){ 
    Log.e("INSIDE ALARM", "INSIDE ALARM"); 
    Intent intent = new Intent(getApplicationContext(), MyService.class); 
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyService.REQUEST_CODE, 
       intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    long firstMillis = System.currentTimeMillis(); 
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 
       6000, pIntent); 
} 

在Reciver

public static final int REQUEST_CODE = 9411; 

@Override 
public void onReceive(Context context, Intent intent) { 
    Intent inti = new Intent(context, LocationService.class); 
    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK); 
    context.startService(inti); 
} 

在IntentService

protected void onHandleIntent(Intent intent) { 
    Log.e("imsidehandler Service", ":="); 
    mRequestingLocationUpdates = false; 
    buildGoogleApiClient(); 
    createLocationRequest(); 
    buildLocationSettingsRequest(); 
    checkLocationSettings(); 
    sendDataServer(); 
} 

public void onConnected(Bundle bundle) { 
    if (mCurrentLocation == null) { 
    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
    updateLocationUI(); 
    } 
} 

public void onConnectionSuspended(int i) { 

} 

public void onLocationChanged(Location location) { 
    mCurrentLocation = location; 
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
} 

public void onConnectionFailed(ConnectionResult connectionResult) { 

} 

private synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

private void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
} 

private void buildLocationSettingsRequest() { 
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); 
    builder.addLocationRequest(mLocationRequest); 
    mLocationSettingsRequest = builder.build(); 
} 

private void checkLocationSettings() { 
    PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(
        mGoogleApiClient, 
        mLocationSettingsRequest 
      ); 
    result.setResultCallback(this); 
} 

protected boolean startLocationUpdates() { 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 
      android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return true; 
    } 

    return false; 
} 

protected void stopLocationUpdates() { 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this).setResultCallback(new ResultCallback<Status>() { 
     @Override 
     public void onResult(Status status) { 
      mRequestingLocationUpdates = false; 
     } 
    }); 
} 

private void updateLocationUI() { 
    if (mCurrentLocation != null) { 
    updateCityAndPincode(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 

    } 
} 

private void updateCityAndPincode(double latitude, double longitude) { 
    try { 
    Log.e("latitude","==>"+longitude); 
    Log.e("longitude","==>"+longitude); 
    this.latitude = latitude; 
    this.longitude = longitude; 
    getGeoAddress(latitude, longitude); 
    } catch (Exception e) { 
    } 

} 

private void getGeoAddress(Double latitude, Double longitude) { 
    Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
    String result = null; 
    List<Address> addressList = null; 
    try { 
    addressList = geocoder.getFromLocation(
       latitude, longitude, 1); 

     if (addressList != null && addressList.size() > 0) { 
     Address address = addressList.get(0); 
     Log.e("address","==>"+address); 
     for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
      result += address.getAddressLine(i); 
      result += " "; 
     } 
     if (result.contains("null")) { 
      result1 = result.replace("null", ""); 
     } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

    public void onResult(LocationSettingsResult locationSettingsResult) { 
    final Status status = locationSettingsResult.getStatus(); 
    switch (status.getStatusCode()) { 
     case LocationSettingsStatusCodes.SUCCESS: 

      startLocationUpdates(); 

      break; 
     case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
      try { 
       status.startResolutionForResult((Activity) getApplicationContext(), REQUEST_CHECK_SETTINGS); 
      } catch (IntentSender.SendIntentException e) { 
      } 
      break; 
     case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
      break; 

    } 
} 

請幫我

+0

確切的問題是什麼?該服務是否不基於基於AlarmManager的定時器機制運行?或者它運行,但你只是沒有收到有效的位置? –

回答

0

getLastLocation()方法只是獲取該設備碰巧知道最後已知位置。有時設備不會「知道」它的位置,並返回null

設備不會自行確定其位置,但僅在某些應用程序請求位置時纔會確定。因此,您的應用現在依賴於其他請求位置更新的應用。

另外,「最後一次知道的位置」在這裏意思是:它可能不是最新的。地點確實帶有時間戳,可用於評估地點是否仍然相關。

我在代碼中的任何地方都看不到requestLocationUpdates()的調用。這可以按照您指定的時間間隔請求最新的位置更新。

onConnected()方法可以有:

public void onConnected(Bundle bundle) {  
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
} 

(該getLastLocation()呼叫可以被刪除。)

而且你IntentService可以實現LocationListener,做同樣的事情onConnected()現在一樣,但只有在一個位置更新已到達:

@Override 
public void onLocationChanged(Location location) { 
    // Cancel the updates after the first one: 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 

    mCurrentLocation = location; 
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
    updateLocationUI(); 

} 

這將是方式用最小的代碼更改來請求和處理位置更新。

當然還有其他一些方法,例如每10分鐘申請一次更新並通過PendingIntent進行處理。有this version of requestLocationUpdates(),需要一個PendingIntent

public abstract PendingResult<Status> requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent) 

將取代當前的定時器機制。