Executing RxAndroid Observables after my application is closed

android rx-java background-process rx-android

386 观看


51 作者的声誉

Is it possible to keep my Observable running after an Android application is closed?

In my example, I have to send the user's location with an interval of 10 seconds. I initially supposed that subscribing on Schedulers.newThread() would do the trick , however , whenever I close the app the process stops. Is there any way I can do this with RxAndroid?

Here is the method that I Use:

private void startShiftLocationUpdater() {

    Observable.interval(10, TimeUnit.SECONDS)
            .flatMap(l -> shouldSendLocation())
            .takeWhile(shouldSend -> shouldSend)
            .flatMap(shouldSend -> initUpdateLocationShift())
            .subscribe(s -> {
                Log.i("ShiftUpdate", "Shift updated successfully");
            }, Crashlytics::logException, () ->
                Log.i("ShiftUpdate", "Shift updated completed")
作者: Fraudlic 的来源 发布者: 2017 年 12 月 27 日

回应 1


4428 作者的声誉


You can use services to continue executing code in background and wakelocks but I had to do something similar at what you describe and found out that services can be killed at any moment if the android system requires free memory.

The solution I found was to use alarms, if you schedule alarms this alarms will be fired whether your app is still executing or not. That way my app could get the device position even though the system had killed the app due to lack of resources. It's the only solution I found that works in this scenario.

The idea came to me in some google i/o when they said that if you really need your app to continue no matter what you should use alarms instead of services.

The only problem I had was that, on some specific Huawei devices, the alarms that had to be executed before 5 minutes from the time they were created just fired after 5 minutes and not at the time you set. So, I finally made a solution involving a service and alarms. This way when an alarm arrived if the service was running the service was stopped and restarted and a position was retrieved. And in that specific Huawei devices the service was always executing sending positions but if, for some reason, the app was killed the alarm would restore everything in less than 5 minutes.

At that moment I didn't use Rx, it was time ago, and using alarms was the solution for not to losing any track of the route. Our app was widely used, I don't say the name only because I don't want to spam here.

I hope I'll explained this alarm issue well. If you need more info just ask.

作者: jeprubio 发布者: 2017 年 12 月 27 日