I would like to share an experience of using the recommended Android way to synchronize your application cache. SyncAdapter is very powerful and at the same time seems to be complex.
Along with features & functionality overview I've provided some leads to start using it right away with sample code.
4. SYNC CACHE: ISSUES TO CONSIDER
Are we done?
Global Sync setting
Bandwidth starvation
YES, queued
YES, even duplicates
YES, even if app is off
YES, built in support
Hand-made SyncAdapter framework
Network availability
Pending queue
Refresh on network
Periodic update
YES, manual override
YES! YES! YES!
4
8. PREREQUISITES TO CONSIDER
Network layer separation
Plain implementation
Sync status field for synced entities
Usually NOOP, Created, Updated & Deleted
Consider the field in UI flows
Consider partial sync
For better performance to sync only local delta
8
9. PUZZLES – ACCOUNT (1)
Key Features
Manage credentials;
Safe system store;
Multitenant support
Sync related
Token caching and invalidation
Alternative flow to login or sign in
Store extra data with account
9
10. PUZZLES – ACCOUNT (2)
Checklist:
Implement Authenticator
Implement Authentication Service
Define configuration in XML
10
11. PUZZLES – ACCOUNT (3)
Checklist:
Register Authentication Service in AndroidManifest
Add permissions
APIs to use:
android.accounts.AccountManager to work with accounts
android.accounts.Account to store credentials
11
12. PUZZLES – CONTENT PROVIDER (1)
Key features
Heart of DAO
Resource effective
Cursor, resource-effective scalability
Power of Joins
Built-in ListView refresh via ContentObserver & Cursor
Sync related
Acts as mediator for sync and UI layers
Supports automatic delta upload sync
NOTE: Can be fake one, but you’ll lose a lot of magic
12
13. PUZZLES – CONTENT PROVIDER (2)
Minimal implementation based on
https://github.com/novoda/SQLiteProvider
Supports all CRUD
Supports DB versioning
And even more…
13
14. PUZZLES – SYNCADAPTER (1)
Key features
Plugin to Android SyncManager
SyncManager manages queue of execution
Adapter is executed in background thread & when
network is available
Sync related
Scheduling & automated mode
Respects system settings
Can be overridden by manual request
Partial sync supported
Upload only local delta
Any other criteria (Bundle) 14
15. PUZZLES – SYNCADAPTER (2)
Checklist
Implement SyncAdapter class
Implement Sync Service
Define configuration xml
15
16. PUZZLES – SYNCADAPTER (3)
Checklist
Register Sync Service in AndroidManifest
Add permissions
APIs to use
android.content.ContentResolver to reach SyncManager
programmatically
16
17. PUZZLES – SYNCADAPTER (4)
How to trigger sync?
Upload delta
ContentResolver.notifyChange
Be aware of cyclic calls if used in ContentProvider
Scheduling
ContentResolver.addPeriodicSync
Automated
ContentResolver.setSyncAutomatically
Manual
ContentResolver.requestSync
Manual forced
ContentResolver.requestSync
Pass SYNC_EXTRAS_MANUAL in bundle
17
19. PROS & CONS
Pros
Simplify server interaction
A lot of work handled by framework
Resource effective – the Android way
Cons
A lot of puzzles, hard to start…
Lack of documentation
Error handling
Bugs
19
21. DOCUMENTATION
Official docs
Great tutorial added in August ’13
http://developer.android.com/training/sync-
adapters/index.html + code sample
Stackoverflow, use tags below
[android-syncadapter]
[sync] + [android]
21
22. BONUS: CODE SAMPLES
Repo on GitHub
https://github.com/springbyexample/spring-by-example
Toy client-server app (both parties supplied )
Shows all puzzles implemented:
Accounts – fake one, there is no authentication
Content Provider based on novoda library
SyncAdapter logics
All wrapping XML configuration
Built via Maven
Follow README and be happy
Got questions?
a.kaverin@gmail.com
22
Introduction. Ask about Android experience, client-server apps and sync adapter knowledge. Session goal.
Define session format – ask questions on current slide content. Complex & conceptual question – Q&A block.
Persisting in cache – Evernote example;off-line mode - no network; capability to create/delete/edit data offline and changes to be applied when back online
What we need to consider to achieve functionality we just mentioned…Network availability – check net before requestPending queue – gather requests if offline, avoid duplicated requests to save battery, like several refreshes, or some upload requests;
Rotation symbol near wifi in HTC Sense;Accounts; Configuration for Google services; Multiple accounts!
Basic flow suggested by the framework; All UI works only with Content Provider; Sync Adapter works with CP;
Let’s see the same picture, but mentioning puzzles we’ll have to implement – 3 items;
Network will be used in 3 places – Login activity, Authenticator – token routines, SyncAdapter network operations;You logic should allow to separate upload from download, as well as an option – to separate synced entities. For example: facebook, sync news, but not contacts at the same time;
How you usually store your app credentials? Prefs or DB? Prefs fine till you got multiple accounts; both pretty safe;Account can have username, password and extra data associated;
Only 2 classes, 1 is almost a dumbstub
Usually CP are avoided, I’m not sure why? ORM fashion?Cursor – allows Android to manage window + fetch exact fields and not whole entity; avoid Cursor to entity mapping when not needed;Joins can allow to do effective cross entity fetch;
DB versioning based on sql file names;
All you code is executed when network is on – but you should be aware that it can be interrupted; Use Sync status to allow repeatable requests;Schedule time intervals, not exact time; intervals may vary;
2 classes, service – is almost a stub; but it is advised to make creation of syncadapter thread safeisAlwaysSyncable – important to make sure it is synced when network available;
notifyChange is usually used from Content Provider;
If you have existing app – it may be wise to drop some of components;Account and ContentProvider can be implemented as stubs; but they must be registered;
Simple – no need to manage threading, define IntentServices, thing of UI callbacks, etc.Framework provides - network check, queue, duplicated requests, etc;Resource – global queue, no channel starvation;Error handling, hard & soft errorsBugs – invalidate tokens; some sync flags ignored. When it works – it’s stable;
Any.do – switched a month ago; Evernote – in June-July.