我正在尝试通过 Google 的 FusedLocationProviderApi 订阅位置更新。我想在后台接收更新,这样即使应用程序被终止我也会收到更新。我尽可能遵循在线文档,编写了以下代码。注意:这是在意图服务中完成的,而不是在 UI 线程上完成的,这就是我使用阻塞连接/结果方法的原因。
private void startLocationServices(String deviceId, int pollingInterval) {
Log.i(TAG, "Starting location services with interval: " + pollingInterval + "ms");
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
final PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire();
final GoogleApiClient googleApiClient =
new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.build();
ConnectionResult result = googleApiClient.blockingConnect();
if (!result.isSuccess() || !googleApiClient.isConnected()) {
Log.e(TAG, "Failed to connect to Google Api");
wakeLock.release();
return;
}
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(pollingInterval);
locationRequest.setFastestInterval(10000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
Intent locationIntent = new Intent(this, GeoBroadcastReceiver.class);
locationIntent.putExtra(EXTRA_LOCATION_UPDATE_DEVICE_ID, deviceId);
locationIntent.setAction(GeoBroadcastReceiver.ACTION_LOCATION_UPDATE);
PendingIntent locationPendingIntent = PendingIntent.getBroadcast(
this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingResult pendingResult = LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, locationPendingIntent);
Result requestResult = pendingResult.await();
Status requestStatus = requestResult.getStatus();
if (requestStatus.isSuccess()) {
Log.i(TAG, "Successfully subscribed to location updates.");
} else {
Log.e(TAG, String.format(
"Failed subscribe to location updates. Error code: %d, Message: %s.",
requestStatus.getStatusCode(),
requestStatus.getStatusMessage()));
}
googleApiClient.disconnect();
wakeLock.release();
}
当我运行这个时,我看到requestStatus.isSuccess()
返回 true,表明我已成功订阅位置更新。此外,GeoBroadcastReciever
,这延伸了WakefulBroadcastReceiver
,以正确的轮询间隔接收意图,并执行正确的操作。到目前为止似乎还不错。这就是我正在做的onReceive
方法为GeoBroadcastReceiver
:
if (LocationResult.hasResult(intent)) {
LocationResult locationResult = LocationResult.extractResult(intent);
Location location = locationResult.getLastLocation();
if (location != null) {
GeoMonitoringService.wakefulLocationUpdate(context, location);
} else {
Log.e(TAG, "LocationResult does not contain a LastLocation.");
}
} else {
Log.e(TAG, "Intent does not contain a LocationResult.");
}
问题是,每当意图出现时,它并不包含LocationResult
,也不包含LocationAvailabilityResult
。我在调试器中检查了传入的意图,意图的附加项中的唯一项目是我在设置意图时添加的附加项(设备 ID)。像这样,LocationResult.hasResult()
返回假。每一次。
我在运行 4.0.1 的 Galaxy Note 4 和运行 5.1.1 的 Nexus 4 上尝试过此操作,结果相同。
如果我在手机上禁用位置,我就会像预期的那样完全停止接收意图。