Reputation: 117
I have an app that connects to the Bitmessage network, i.e. 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
Upvotes: 0
Views: 2601
Reputation: 1409
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.
Upvotes: 1
Reputation: 199880
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.
Upvotes: 6