내 제어 흐름이 IntentService
(GcmListenerService에 의해 트리거 됨)에 있으며 이제 사용자의 위치를 가져와야합니다.requestLocation IntentService에서 5 번 시작되었습니다.
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
이 null
를 반환 할 수 있습니다, 나는 어떤 위치 업데이트를 요청해야합니다. 나는 매번 업데이트 할 때 위치가 GPS 메카닉 때문에 이전보다 더 정확하다고 가정합니다. 정확한 측정을 위해서는 5 회의 측정/업데이트가 충분해야한다고 생각합니다. 해당 로직을 IntentService
에 어떻게 구현할 수 있습니까? 이 클래스는 리스너 인터페이스를 구현합니다
public class LocationIntentService extends IntentService
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
이 방법 나는 public void onLocationChanged(Location location)
에서 카운터를 사용하고 다섯 업데이트 후 LocationServices.FusedLocationApi.removeLocationUpdates()
를 호출 할 수 있습니다. 그러나 나는 IntentService
이 길어서 onHandleIntent
이 완료되면 바로 가비지 컬렉터에 의해 제거되지 않는다는 Android를 신뢰할 수 있는지 잘 모르겠습니다.
public class LocationIntentService extends IntentService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
public LocationIntentService() {
super("LocationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
System.out.println(result.toString());
}
@Override
public void onConnected(Bundle connectionHint) {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int cause) {
}
private void displayLocation(Location location) {
System.out.println(location.toString());
DbHandler dbHandler = new DbHandler(getBaseContext());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
double altitude = location.getAltitude();
float speed = location.getSpeed();
long time = location.getTime();
float accuracy = location.getAccuracy();
PersistedLocation persistedLocation = new PersistedLocation(time, latitude, longitude, altitude, accuracy, speed);
dbHandler.insertLocation(persistedLocation);
}
@Override
public void onLocationChanged(Location location) {
displayLocation(location);
}
}