I'd like to detect when there is a network change (connection\disconnection) when my app is not in the foreground, so I can sync the user's data.
I have tried to use a broadcast receiver
(like in this answer) but the broadcasts are no longer received when the app is closed (after Android N
). It only works when the app is in the foreground.
In order to detect connectivity change in the background, I have tried to use the Job Scheduler
(like in this answer) with the .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
parameter, but my problem is that the job is done repetitively (every 15 minutes), even when the user is still connected to the internet.
My goal is to make the job once when the internet connection is regained, and then stop the job until the user disconnects and connects again. The job should be done once for every connection to the internet, and then wait until a reconnection (without repeating it).
Is it possible to achieve this with the Job Scheduler
(or in any other way)?
Is it possible to achieve this with the Job Scheduler?
Answer - I don't know BUT
You can use WorkManager. That is part of Android Jetpack.
There are 2 options.
1) OneTimeWorkRequest (that what you need).
2) PeriodicWorkRequest (executes periodically, min time is 15 minutes, same as jobScheduler).
WorkManager executes only 10 seconds, as jobscheduler.
Why is WorkManager good. Image in below will give answer.
Documentation - https://developer.android.com/topic/libraries/architecture/workmanager