降低电池消耗的建议,您可以使用活动检测来确定您需要多久确定一次位置。在这方面,我可以推荐https://github.com/mcharmas/Android-ReactiveLocation,我在其中贡献了活动检测部分。该库还大大减少了获取融合位置所需的编码行数。
该库在此处包含一个简单的使用示例:https ://github.com/mcharmas/Android-ReactiveLocation/blob/master/sample/src/main/java/pl/charmas/android/reactivelocation/sample/MainActivity.java
正如您在评论中所写,要找到使用 ActivityDetectionApi 的好例子并不容易。这也是我将其添加到库中的原因之一。事实上,当时 google 提供的文档已经过时,因为他们更新了 Google Play Services API,但没有更新教程。
对于不使用该库的教程,我没有任何好的指导,但我可以使用 ReactiveLocation 提供我的代码片段。此代码在服务中运行,因此无论应用程序是否处于焦点,它都会跟踪当前活动:
private void requestFilteredActivityUpdates() {
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getApplicationContext());
filteredActivitySubscription = locationProvider.getDetectedActivity(0).doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String message = "Error on activitySubscription: " + throwable.getMessage();
Log.e(TAG, message, throwable);
Crashlytics.logException(throwable);
}
}).onErrorReturn(new Func1<Throwable, ActivityRecognitionResult>() {
@Override
public ActivityRecognitionResult call(Throwable throwable) {
List<DetectedActivity> list = new ArrayList<DetectedActivity>();
list.add(new DetectedActivity(DetectedActivity.UNKNOWN, 0));
return new ActivityRecognitionResult(list, System.currentTimeMillis(), SystemClock.elapsedRealtime());
}
}).filter(new Func1<ActivityRecognitionResult, Boolean>() {
@Override
public Boolean call(ActivityRecognitionResult activityRecognitionResult) {
DetectedActivity detectedActivity = activityRecognitionResult.getMostProbableActivity();
boolean highConfidence = detectedActivity.getConfidence() > 75;
DetectedActivity previousActivity = ActivityDetectionModule.Recent.getDetectedActivity();
boolean isNewActivity = detectedActivity.getType() != previousActivity.getType();
boolean hasHigherConfidence = detectedActivity.getConfidence() > previousActivity.getConfidence();
return mJustStarted || (highConfidence && (isNewActivity || hasHigherConfidence));
}
}).subscribe(new Action1<ActivityRecognitionResult>() {
@Override
public void call(ActivityRecognitionResult activityRecognitionResult) {
DetectedActivity detectedActivity = activityRecognitionResult.getMostProbableActivity();
Log.i(TAG, "Activity changed or increased in confidence:");
Log.i(TAG, "New: " + ActivityDetectionModule.getNameFromType(detectedActivity.getType()) + " confidence: " + detectedActivity.getConfidence());
}
});
}
在onDestroy()
我打电话
public void unsubscribeActivityUpdates() {
unsubscribe(filteredActivitySubscription);
}
private void unsubscribe(Subscription subscription) {
if (subscription != null && !subscription.isUnsubscribed()) {
Log.i(TAG, "Unsubscribe activity updates");
try {
subscription.unsubscribe();
} catch (Exception e) {
e.printStackTrace();
}
subscription = null;
}
}
我希望这足以说明如何使用该库,否则请随时提问。