2

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)?

Tal Barda
  • 4,067
  • 10
  • 28
  • 53
  • work manager is a good option for this. as it will decide to run broadcast of network or it use job scheduler. – unzila Apr 21 '19 at 18:12

1 Answers1

2

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. enter image description here

enter image description here

Documentation - https://developer.android.com/topic/libraries/architecture/workmanager

Hayk Mkrtchyan
  • 2,835
  • 3
  • 19
  • 61
  • Thanks. Can you please add a code example? I'm not familiar with this tool at all. – Tal Barda Apr 21 '19 at 18:35
  • 1) https://www.youtube.com/playlist?list=PLk7v1Z2rk4hgI250AJXKsQH_4X3gRRaMg - Video tutorials, I think one of the best )) – Hayk Mkrtchyan Apr 21 '19 at 19:24
  • 2) Google codelabs tutorial - https://codelabs.developers.google.com/codelabs/android-workmanager/#0 I think this will help you to understand this. If my answer helped, please give vote and accept it :) Good luck )) – Hayk Mkrtchyan Apr 21 '19 at 19:28