【发布时间】:2017-08-07 12:23:08
【问题描述】:
Android 设备监视器:
我的位置更新服务每秒接收数千个意图。我不确定是什么触发了它
实例化和调用 Fused Location,我实现了GoogleApiClient.ConnectionCallbacks,所以我可以在收到onConnected 时启动位置请求
private GoogleApiClient mGoogleApiClient;
private boolean mInProgress = false;
private static int INTERVAL = 10*60*1000;
private LocationRequest mLocationRequest;
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(20)
.setFastestInterval(INTERVAL)
.setInterval(INTERVAL);
intent = new Intent(this.getApplicationContext(), LocationUpdateService.class);
pendingIntent = PendingIntent.getService(this.getApplicationContext(), 0, intent, 0);
Log.d(TAG, "on create");
}
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "Connected to FusedLocationAPI");
mInProgress = false;
Log.d(TAG, "Fastest interval : " + mLocationRequest.getFastestInterval());
Log.d(TAG, "interval : " + mLocationRequest.getInterval());
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, pendingIntent);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) Log.d(TAG, location.toString());
}
接收位置的我的更新服务很简单,它会调用另一个服务来处理位置数据
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (LocationResult.hasResult(intent)) {
LocationResult locationResult = LocationResult.extractResult(intent);
Location location = locationResult.getLastLocation();
sIntent = new Intent(this, DoWork.class);
sIntent.putExtra("LATITUDE", location.getLatitude());
sIntent.putExtra("LONGITUDE", location.getLongitude());
startService(intent);
Log.d(TAG, "onStartCommand has Intent : " + startId);
stopSelf(startId);
} else {
Log.d(TAG, "onStartCommand no Intent");
}
return START_STICKY;
}
如果我注释掉 LocationServices.FusedLocationApi.requestLocationUpdates 行,则意图不会按预期触发,因此我会认为请求构造错误,或者我没有正确处理意图以表明我已经处理了它,我找不到与其中任何一个相关的任何内容
【问题讨论】:
标签: android location android-pendingintent fusedlocationproviderapi