Android: Scheduling long background task when syst

2019-08-28 22:31发布

问题:

I'm writing an Android application that records video and then runs post processing on recorded video. Since post processing may take a while (up to an hour) I'm scheduling a service - JobService using JobScheduler to run when the phone is connected to power and idle i.e. to run at night. The job service doing the long-running job on a new thread.

In practice my scheduled service is working VERY slow. It seems that although it runs when system is idle, it gets very little CPU bandwidth. Also my service is being stopped after 10 minutes max by the OS.

I know Android Oreo limits background processing. This is well documented by Google. However I'm wondering if there is a way to run background services when system is idle.

Is there a way to run long background services when system is idle? For example video post processing?

回答1:

You need to use a Foreground service.

They are one of the few methods left to run long background tasks. The user must know what's happening on his device and he should have the ability to decide to stop it or not.

You can read how to implement basic Foreground Services here, and there are a lot of guides on the internet on how to implement them in an advanced manner.

Remember that even a Foreground Service can be stopped by the OS if the system is in extreme memory pressure and the only things left to destroy are foreground services. So you should always have a recovery procedure if that happens.