Synchronization with ASyncTask on android - android

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.

Related

Kotlin, WorkManager scheduled repeatedly once in a week

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.

Implementing both requestSync and periodicSync in the same app

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?

Posting data to server every 15 minutes using Sync Adapter and Alarms

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.

Android Sync Adapter Intervals

I require a data sync once per day for an Android application. I've been using Sync Adapter which has been very useful. I want to sync the data only once per day (at no specific time). I'm using the addPeriodicSync() method.
My problem is that users are only likely to enter an area with internet access for very short periods at different times of the day (sometimes not in internet access areas for days at a time). I have the sync interval at 1 day, will the sync process be run as soon as the internet becomes available? or will it only attempt to sync when the period sync timer is triggered?
Additionally, are there any options to enable/disable 3G/Mobile internet syncs?
Yes by design sync adapters will queue all sync request in absence of network , also if user asks for manual sync when auto sync is already in queue then it will handle it . That's the beauty of sync adapter design

Android: Recommended workaround for google-drive-sdk timeout issue?

When a network connection is unavailable, the drive sdk takes a very long time to timeout -- it takes 15 mins according to this answer.
I access Drive in an AsynchTask which blocks my application. So, if there is no network connection, the application shows a ProgressDialog for 15 mins, until the time out. Possibly I could implement my own timer which kills the AsynchTask after a reasonable duration. However, it might be difficult to differentiate between a timeout and a lenghty process (like downlaoding a large file on a slow connection) and I would be concenred that there could be issues with the token access not cleaning up properly. Any suggestions for how to work around this?
A check if there is a network connection before performing the AsyncTask would help eliminate a lot of the cases, see Detect whether there is an Internet connection available on Android

Categories

Resources