让我们假设我们在某些广播中从BrodcastReceiver开始提供服务。可以在onReceive()返回之后和服务启动之前杀死进程吗?如果是这样,如何防止这种行为?
答案 0 :(得分:1)
如果BroadcastReceiver
已调用Context.startService()
并且它收到了非null
ComponentName
对象,则不会。这意味着在系统中找到了Service
,并且已经开始了#34}。请注意,开始是异步的,因此在接收方退出其Service
回调之前,onStartCommand()
无法保证onReceive()
已收到BroadcastReceiver
回调。
另请注意,即使Service
已启动Service
,默认情况下这对电源管理也没有影响。因此,在设备完全启动并运行之前,您的BroadcastReceiver
可能无法回叫 - 它可能会在Service
完成后但public class LocationCollectionRepository {
private final static Integer fetchInterval = 30; //Minutes
private final LocationService locationService;
private final LocalLocationCollectionRepository localRepository;
public LocationCollectionRepository(@NonNull LocationService locationService, @NonNull LocalLocationCollectionRepository localRepository) {
this.locationService = locationService;
this.localRepository = localRepository;
}
public Observable<LocationCollection> getLocationCollection() throws IOException {
return localRepository.getLocationCollection()
.takeWhile(this::shouldFetch)
.flatMap(remoteCollection -> fetchLocationCollection())
.takeWhile(this::isRequestSuccessful)
.flatMap(locationCollectionResponse -> persistLocationCollection(locationCollectionResponse.body()));
}
//================================================================================
// Private methods
//================================================================================
private Observable<Response<LocationCollection>> fetchLocationCollection() throws IOException {
return Observable.fromCallable(() -> {
LocationServiceQueryBuilder queryBuilder = LocationServiceQueryBuilder.query();
return queryBuilder.invoke(locationService).execute();
});
}
private Observable<LocationCollection> persistLocationCollection(@NonNull LocationCollection locationCollection) {
return localRepository.saveLocationCollection(locationCollection);
}
private boolean shouldFetch(@NonNull Optional<LocationCollection> locationCollection) {
if (locationCollection.isPresent()) {
Interval interval = new Interval(new DateTime(locationCollection.get().getTimestamp()), new DateTime());
return locationCollection.get().getHashValue() == null || interval.toDuration().getStandardMinutes() > fetchInterval;
} else {
return true;
}
}
private boolean isRequestSuccessful(Response<LocationCollection> locationCollectionResponse) throws Exception {
if (locationCollectionResponse == null || !locationCollectionResponse.isSuccessful()) {
throw new Exception(locationCollectionResponse.message());
}
return true;
}
运行之前重新进入休眠状态