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
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.