is there any way to reset the period of a PeriodicSync??
I mean, if the period is 10 mins, 7 mins have passed since the last sync, reset the period so next sync would by within 10 mins again, not 3.
ContentResolver has no methods for this. I've tried to:
Invoke ContentResolver.addPeriodicSync() over an existing PeriodicSync. As stated in the javadocs the period gets updated, but not resetted.
Stop and start the PeriodicSync. In this case the sync gets triggered when restarting, what I don't want to.
Thank you.
I have similar problem and not found way to update settings only:
ContentResolver.removePeriodicSync
and
ContentResolver.addPeriodicSync
change settings and as You write it runs sync
Related
I have an app where user can scan details from his device and send details via https to my backend service so I can evaluate his data and send other data back to his mobile device.
Now I need to implement background task which would do previously mentioned scan once in a week, let's say on friday even when the application is not running. I don't want to send back to device any data if scan is run in background task not from user directly. I just need to send data from device to service.
I would like to choose the best solution which seems like WorkManager with periodic work request (https://developer.android.com/reference/androidx/work/PeriodicWorkRequest). However I have few questions.
Let's say I would like to make a scan every friday. Only constraint is that user has to be connected to the internet. If user install my application and execute it on monday I would set the repeat interval for 5 days and flex interval for 1 day. So background work should be executed last day which is friday. But after this background scan, period should change from 5 days to 7 days, so it can execute every next friday. How can I make this change? Should I run OneTime background work which run scan after 5 days and create repeated background task with 7 days period?
If user is not connected to internet all friday, is it gonna take another period (7 days in this case) since next execute or will it execute on saturday? If not on saturday, what should I do to run it on saturday?
If user is not connected to internet for half of friday, it is going to execute my background work on friday afternoon with 7 days interval and 1 flex day interval. However since the user wasn't connected for half day, next background work will be execute from friday afternoon to saturday midday? Or will it execute only in friday just like previous work? If not how can I prevent this behaviour?
If Work Manager can't ensure, that background task will be executed on friday, what should I use than. I think that one day is a quite huge interval and it shouldn't be such problem, right?
I am grateful for every opinion and advice.
Since that time I put here the question I have gained some experience so I am going to type some advice for users with same questions.
If you want to proceed background task once per several days, I recommend you to set period interval for one day and check if last time that background work was processed was already your expected period. For example if you want period once per week, set the period for one day. In every day background work check if last work was before 7 days. With this condition if background is not processed after 7 days, it will be started after 8 days or 9 days but not after 14 days as it would be if period was set on 7 days.
I also recommend you to check battery in your mobile settings, find your application and make sure, that your application will no be forced stop due to battery optimalization. Because force stop will also kill your background work.
I need to implement requestSync on button click and additionally periodic sync. I'm aware that requestSync isn't best practice, but that's just requirement, I have to do it.
Questions are:
1) if I set up periodic sync's pollFrequency to be 24hrs, and requestSync happened before 24hrs passed, will periodic sync will start counting from clean slate after requestSync or it will sync after 24hrs again?
2) What will happen if requestSync happened at the same time as periodic sync?
3) In the documentation it says pollFrequency has to be minimum 1hr, however I'm testing with 20 sec pollFrequency. Why is this possible?
4) syncing is happening not in 20 seconds but with varying intervals: 60secs, 5 secs, etc. Is this normal for intervals to be so different from each other?
5) Do I have to set some type of flag in the activity I'm setting periodic sync, that if it is first time the activity is being opened then set periodic sync, otherwise skip? Or system will know better than resetting same sync many times?
Requirement - I need to get the user's location coordinates every 15 minutes roughly and post it to the server. It is necessary to post data roughly at these intervals.
Implementation - I've made a sync adapter instead of using AlarmManager as it saves battery. I've set ContentResolver.addPeriodicSync() to sync my app every 15 minutes roughly which gets the current location and posts to server.
Problem - In case there's no internet connection, I want to continue taking the user's location every 15 minutes and save them in the local sqlite database. When the internet comes back again next time then I'll post all the saved locations in one go so that server data remains consistent and after that sync will resume as normal.
The main problem is that when there's no internet then the sync stops and I stop getting periodic sync callbacks in my app and I'm not able to save data in the local database. So what I want is that even when there's no internet I keep getting callbacks at regular intervals till the internet comes back and auto sync starts again. Can the sync adapter do that?
One solution I can think of is that I get a broadcast when the Internet stops and at that moment I start using the AlarmManager to start a service every 15 minutes and get the location and save to local database. And when the internet comes back on then I stop using the AlarmManager and go back to auto syncing.
Solution 2 - Provided by David Medenjak below. It is also efficient due to AlarmManager's setInexactRepeating() behavior which tries to imitate Sync adapter's behavior by scheduling Alarms for different apps together to reduce the number of times the CPU wakes up. Also it leads to a little simpler implementation. Would this the better way than the previous solution comparing the pros and cons?
Still any better way to achieve this?
You are mixing two things:
Getting the user location every 15 minutes
Syncing the data with the server
If you start mixing those you have a service and sync adapter that are both strongly dependent on each other, you have to check for states which of those has run and which should run. You might end up with the exact thing that you want (syncing every 15 minutes, just cache it if user is offline) but it will be hard to test and maintain.
Always use a service that is run every 15 minutes to store the current user location.
Periodically sync all updates to the server. This may also happen to be every 15 minutes, but you should not depend on this.
By having one part just storing the location and the other part just synchronizing the data you will have a much easier time handling things. And you also don't have to worry about internet connection or the interval of the synchronizations (since sync adapters are not guaranteed to run at exact times).
Concerning battery life (comments)
There should be no big difference whether a SyncAdapter uses gps and posts it immediately or a service persists it for the time being until the adapter syncs it. As soon as a task has to run every x minutes the device will have to wake up.
There might be slight improvements if the synchronization is run at a slower rate compared to the service, since the gps alone might not need any internet connection.
IntentService - runs every 15 min (using AlarmManager) and saves the user location in the db and mark it as unsent.
SyncAdapter - runs every 15 min and ties to send all unsent locations to the server. On success mark the location as sent. Android will make sure it's only run when there is a internet connection.
Edit:
The key point is separating the two sub-tasks (also suggested by #David Medenjak):
1) Get a location update and store it in a db
2) Send the location updates to the server when there is a network connection.
The FusedLocationProvider has a method
requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
for when your app is in the background. Link
This method is suited for the background use cases, more specifically
for receiving location updates, even when the app has been killed by
the system.
You can use a LocationRequest to set the priority, interval, power consumption. Link
When you receive the pending intent, you can insert the location in the database and request a sync using the sync adapter.
I can get the time change events with the help of broadcast events (ACTION_TIME_CHANGED and ACTION_DATE_CHANGED).
I need to get the previous time after time change. For example, the current time is 10:00. I am going to change time to 12:00. After time change, time will be changed to 12:00, but I need to get the previous time (10:00) at the time of time change.
Note: Time can be changed from any other app or from settings.
Maybe the solution I found can help you:
(Is there a way to detect when the user has changed the clock time on their device?)
The above solution could work setting a static variable on BOOT of device with System.currentTimeMillis(), and sum with SystemClock.elapsedRealtime(). With this sum you have the before time.
But there is a problem (I don't know if it matters to you), if the user does not reboot the device, then your diff will be == 0 and you will not be able to have this diff between old and actual System.currentTimeMillis().
At the time of change timing task just store current or old time millisecond in sharedpreferences i.e u can use any time even app will not in stack it self
I am thinking about implementation of synchronization in my android application with ASyncTask and AlarmManager. Tried to do the same with SyncAdapter, but it just complicates the process and has other disadvantages (ContentProvider is needed, manual sync seems to be impossible if automated is disabled, user is needed etc.).
So, the question I have now with ASyncTask - let's say, it is started every 24 hours. But in case if there is not internet connection at this time, synchronization will not happen. Next time attempt will happen after 24 hours again. What can I do to avoid this? I.e. if 24 hours are already passed, then any time internet connection appeared, the task should be run. After this moment next 24 hours to be counted.
For ex.,
sync 1 - day 1 12:00 (successful)
sync 2 - day 2 12:00 (failed - no internet connection)
sync 3 - day 2 20:00 (successful, internet connection appeared)
sync 4 - day 3 20:00 (successful)
Believe, I can either run my task more often (for ex., each 30 minutes) and store time of last update somewhere. Or, I can listen for event when internet connection appears. What is the best approach? Or, is there some standard functionality for the same?
I would go with the BroadcastListener registered to do the syncing when internet connection is available. You could use the SharedPreferences to indicate for this listener, that sync is needed - because I guess you'd have to register this listener in the manifest, I think there's no way to handle this dynamically.
This way you can be sure that sync will happen if there's net connection available, while the 30-min-polling might miss the chance.