简体   繁体   中英

How to work around the Android JobScheduler timeout?

I have an app that connects to the Bitmessage network, ie is downloading and processing data from the P2P network all the time. Also, it should (optionally) only use WiFi/unmetered networks.

I've implemented this by using the JobScheduler, but unfortunately it has a timeout of 10 minutes (apparently even 1 minute on Lollipop).

So in short, how do I implement a service that

  • automatically starts when WiFi is available
  • automatically disconnects when a metered network is used
  • doesn't time out
  • works on all Android versions since Lollipop

As you've found, a JobScheduler is not the correct component for continuously running in the background. The correct component for that is a foreground service .

From your requirements:

  • automatically starts when WiFi is available

You should still use JobScheduler for this. Your JobScheduler doesn't do any work itself: it just starts your foreground service. You can use Firebase JobDispatcher if you'd like it to work back to API 14 and only need to run on devices with Google Play services.

  • automatically disconnects when a metered network is used

In your foreground service, you should programmatically register a listener for the CONNECTIVITY_ACTION Broadcast. In the callback, you should check the result of isActiveNetworkMetered() (available on API 16) and, if true, stop your foreground service.

  • doesn't time out

A foreground service has no time out: it'll continue to run until you stop the service. It is highly recommended that the notification required to make a service a foreground service have an action to allow the user to stop your service manually.

As mentioned, the job scheduler is not intended for tasks that run forever. That is what foreground services are for.

In your case, I'd suggest using a job to monitor for the startup constraints that you want (metered network and so on). When that job runs, you start a foreground service to do the actual work, and return false from onStartJob().

Then, while your foreground service is running, just watch for the loss of metered networking directly using the connectivity & network APIs, and shut down the foreground service when appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM