在我的应用程序中,我使用 ReactiveLocationProvider 来获取后台位置更新。(库链接)当我的应用程序最小化(进入 onPause)时,它开始接收更新。它工作正常,但问题是我不希望频繁更新。例如,在我的代码中,我有一个 LocationRequest,它应该在用户移动 1 公里并且至少 10 分钟(setFastestInterval)已经过去时获取位置更新(一个)。根据我的日志,我收到的更新超出了需要。有谁知道为什么?
这是我在 MainActivity on create 方法中的代码:
public class MainActivity extends AppCompatActivity {
LocationRequest request;
ReactiveLocationProvider locationProvider;
Subscription subscription;
Subscription onlyFirstTimeSubscription;
NotAbleToGetWeatherDataTask mNotAbleToGetWeatherDataTask = new NotAbleToGetWeatherDataTask();
int numOfBackgroundUpdates = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------MY CODE STARTS HERE-----------------
request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setSmallestDisplacement(1000)
.setFastestInterval(10 * 1000)
.setInterval(30 * 60 * 1000);
locationProvider = new ReactiveLocationProvider(this);
}
和我的 onPause 方法:
@Override
protected void onPause() {
super.onPause();
//subscribe for background location updates...
subscription = locationProvider.getUpdatedLocation(request)
.subscribe(new Action1<Location>() {
@Override
public void call(Location location) {
Log.d(TAG, "Getting Background updates...");
MainActivity.this.latitude = location.getLatitude();
MainActivity.this.longitude = location.getLongitude();
numOfBackgroundUpdates++;
}
});
}
我正在取消订阅销毁请求:
@Override
protected void onDestroy() {
Log.d(TAG, "OnDestroy Called!");
subscription.unsubscribe();
super.onDestroy();
}
最近的日志(我已经移动了 1 公里并且至少已经过去了 10 分钟)
12-28 17:12:25.564 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.918 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.924 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.925 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.927 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.928 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.930 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.931 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.940 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.942 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.942 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.946 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.949 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.951 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.951 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:06.951 29845-29845/? D/MainActivity: Getting Background updates...
12-28 17:16:40.371 29845-29845/? D/MainActivity: Getting Background updates...