【发布时间】:2016-04-13 12:03:21
【问题描述】:
我想在后台每隔几分钟更新一次用户的位置。
我使用了这个示例代码googlesamples/android-play-location
但将其更改为与Service一起使用
public class MyService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, ResultCallback<LocationSettingsResult>
但我无法检查位置设置
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
}
@Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" +
"upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " +
"not created.");
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
break;
}
break;
}
}
因为这个方法需要Activity
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
如果我将之前的代码放在 MainActvity 中,我将没有对 mGoogleApiClient 和 mLocationSettingsRequest 的引用
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, mLLocationSettingsRequest);
即使活动被破坏,我也想升级并在后台保存位置。
使用该服务的正确方法是这样做的吗?
我如何检查位置设置?
[编辑]
我尝试使用PendingIntent 和IntentService
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, mPendingIntent);
此方法适用于后台用例,更具体地说 用于接收位置更新,即使应用程序已被 系统。
与Service和LocationListner的版本相比有什么不同?
【问题讨论】:
标签: java android service location fusedlocationproviderapi