【发布时间】:2017-02-11 12:53:24
【问题描述】:
我的控制流位于IntentService(由 GcmListenerService 触发)中,现在应该可以获取用户的位置。作为
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
可能会返回null,我应该请求一些位置更新。我假设每次更新时,由于 GPS 机制,位置都比以前更准确。我想五次测量/更新应该足以获得准确的位置。
如何在IntentService 中实现该逻辑?该类实现了监听器接口:
public class LocationIntentService extends IntentService
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
这样我可以在public void onLocationChanged(Location location) 中使用计数器并在五次更新后调用LocationServices.FusedLocationApi.removeLocationUpdates()。但是,我不确定我是否可以相信 Android 相同的 IntentService 寿命那么长,并且不会在 onHandleIntent 完成后立即被垃圾收集器删除。
这是我目前使用的完整代码,没有收集仅五个更新的逻辑:
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);
}
}
【问题讨论】:
标签: android android-location android-intentservice android-googleapiclient