mdevcon - A Primer to SyncAdapters


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

mdevcon - A Primer to SyncAdapters

  1. 1. A PRIMER TOSYNC ADAPTERS Kiana Tennyson mdevcon Tuschinski Theater March 2013
  2. 2. OVERVIEWv Who is Kiana?v SyncAdapter Use Casesv The Big Picturev Configurationv Authorization, Content, Synchronizationv Wrap up/Questions
  3. 3. WHO’S KIANA?v Software Developerv Professional background working on web portalsv Work at Manheim, wholesale vehicle auction companyv Customer facing applications •  Web portal ( Ruby, Java, JS •  iOS app •  Android app
  4. 4. SYNC ADAPTERS ARE…?v Share data between a remote data source and an Androiddevicev Android OS provides plug-in architecture that takes care of: •  Coordinating network availability with syncing all datasources •  Scheduling synchronization/Handling stopped processes •  Accommodating user preferences when syncing •  Handling network interruptions
  5. 5. TOUGH PARTSv Good news! Writing a Custom SyncAdapter is actually easy!v Bad news. There are potentially tough parts: •  Authentication Handling •  (Custom) Content Provider •  Data Handlingv Defined by business rules
  6. 6. BEST USE CASESApplication that…v Requires authentication step to connect to remotedatasourcev Potentially could use a built-in ContentProvider •  All providers found in android.provider packagev Application Suite backed by custom ContentProvider
  7. 7. !(BEST USE CASES)v Anything that DOES NOT require a loginv Any source that provides an RSS feed •  Typically public data sources like news/media sites •  Write a parser that reads the feed only when the user wants it •  SyncAdapter not necessary to write to the ContentProviderv If Service does not constantly need to run in thebackground •  User has limited battery power, code with this in mind
  8. 8. A Primer to SyncAdaptersCONFIGURATION
  9. 9. THE BIG PICTUREAccountManager SyncManager ContentProvider •  Requires •  Uses Account •  Holds the data Authentication List as a basis for •  Called in Service to add it’s Sync List onPerformSync() Account •  Requires Sync •  Adds Account to Service to start Account List data syncs
  10. 10. AUTHENTICATIONv Write an AuthActivity •  serves UI for user to enter account info •  Write it to complete the authorization processv Write an Authenticator •  MUST extend AbstractAccountAuthenticator •  Returns the AuthActivity in a Bundle objectv Write an Authentication Service •  MUST extend Service •  onBind return IBinder for the Authenticator
  11. 11. SYNCHRONIZATIONv Write a SyncAdapter •  MUST extend AbstractThreadedSyncAdapter •  Overwrite onPerformSync()v Write a Sync Service •  MUST extend Service •  Allow creation of ONE SyncAdapter •  onBind returns a IBinder for SyncAdapter
  12. 12. RESOURCE XMLSv Provide configuration infov Map account type to objects •  SyncAdapter and Authenticator are connected via android:accountTypev Map content authority to SyncAdapter
  13. 13. RESOURCE XMLS<?xml version="1.0" encoding="utf-8"?>!<account-authenticator xmlns:android="http:// !”! android:accountType=”"! android:icon="@drawable/icon"! android:smallIcon="@drawable/icon"! android:label="@string/label"!/>!
  14. 14. Add Accountv  Notice result of android:iconv  Green lights – Account addedv  Gray lights – Account not addedv  Clicking one launches Auth Activity interface
  15. 15. RESOURCE XMLS<?xml version="1.0" encoding="utf-8"?>!<sync-adapter xmlns:android="http:// !”! android:contentAuthority=""! android:accountType=""! android:supportsUploading="false"! android:userVisible="true"!/>!
  16. 16. MANIFESTv Several appropriate permissionsv Declare AuthenticationService with <service> tag •  Intent filter: “android.accounts.AccountAuthenticator” •  Meta-data tag points AccountAuthenticator to xml resource filev Declare SyncService with <service> tag •  Intent filter: “android.content.SyncAdapter” •  Meta-data tag points SyncAdapter to xml resource file •  Other Meta-data tag defines custom MIME-typesv Declare AuthActivity (no Intent filter necessary)
  17. 17. MANIFEST.XML<service android:name=".authenticator.AuthenticationService” !android:exported="true”>! <intent-filter>! <action android:name="android.accounts.AccountAuthenticator" />! </intent-filter>! <meta-data android:name="android.accounts.AccountAuthenticator”! !android:resource="@xml/authenticator" />!</service>!<service android:name=".syncadapter.SyncService” android:exported="true">! <intent-filter>! <action android:name="android.content.SyncAdapter" />! </intent-filter>! <meta-data android:name="android.content.SyncAdapter”! !android:resource="@xml/syncadapter" />! <meta-data android:name="android.provider.CONTACTS_STRUCTURE”! !android:resource="@xml/contacts" />!</service>!
  18. 18. WHY SERVICES?v SyncAdapter is bound to a service, Authentication is bound to aservice… but why?v SyncManager finds all syncAdapters via a SyncAdaptersCache.v AccountManager finds all Accounts via AccountAuthenticatorCachev RegisteredServicesCache •  Reads the XML files created (account-authenticator and syncadapter) •  Generates service maps
  19. 19. CODE SUMMARYv Create a syncadapter.xml filev Create an authenticator.xml filev Add an authentication <service> to manifestv Add a sync <service> to manifestv Add correct permissions to manifestv Write some java… but what does any of this mean?
  20. 20. A Primer to SyncAdaptersTHE DATA
  21. 21. ACCESSING CONTENT •  SharedPreferences Data Storage •  External Storage •  SQLLiteDatabase ContentProvider ContentProviderClient ContentResolver Context Android Application(s)The Device User
  22. 22. CONTENT PROVIDERv Manages central repository of data.v SyncAdapters wouldn’t exist without ContentProviders •  SyncAdapter mentioned in ContentProvider section of API Guidev Built in ContentProviders contain a SyncState table •  Use to store sync state, meta-data or any sync related datav Sync related columns in other tables: •  DIRTY, VERSION, SOURCE_ID
  23. 23. IMPORTANT COLUMNSv DIRTY (local modifications) •  Indicates data row has been changed locally since last sync. •  When SyncAdapter adds/updates a row, append “CALLER_IS_SYNCADAPTER” to Content URIv VERSION •  Incremented by Provider whenever the data row is changed. •  High-water marking (aka lastSyncState)v SOURCE_ID •  Unique ID for data row (primary key on the remote datasource) •  If set to null, indicates to SyncAdapter to create new row on remote source
  24. 24. CUSTOM CONTENT PROVIDERv What properties make the built-in ContentProviders“syncable”? •  Extra “For Sync use only” table that holds metadata •  “CALLER_IS_SYNCADAPTER” query param •  Use of “high-water-mark” is essentialv These properties should be applied to Custom SyncAdapter
  25. 25. CONTENT RESOLVER VS CONTENTPROVIDER CLIENT ContentResolver ContentProviderClientv  Thread safe v  Not thread safev  Many calls to many v  Repeated calls to same CA ContentAuthorities (CA) v  Cheaper call (one CA lookup)v  Expensive call (Many CA lookups) v  You MUST call release() to avoidv  Resolver contains a Client memory leak
  26. 26. CONTENTPROVIDER CLIENTv Part of onPerformSync() method signature.v Not thread safe, so be careful with usage •  Utilize locking strategies, ensure no outside services are performing activities on sync-candidate datav Android Sample project uses threadsafe ContentResolvervia a Manager
  27. 27. CONTENT RESOLVERv Do I really need this? Your choice. •  ContentResolvers query the ContentProvider •  Use it to CRUD data inside syncAdapter.onPerformSync(); •  SampleSyncAdapter uses the ContentResolver by way of it’s ContactsManager class, because it performs batch operationsv Retrieve it using: context.getContentResolver();v However, there are other ways to access the data
  28. 28. DATA CONSIDERATIONSv Determine structure of serialized/transmitted data •  Using json? xml? yaml? •  What does a single row (data unit) look like?v How does the server parse and save the transmitted data? •  Likely defined by business limitations.v How does the device parse/save the data? •  ContentProviderClient or ContentResolver (batch ops)
  29. 29. A Primer to SyncAdaptersAUTHENTICATION
  30. 30. ACCOUNTv Account object contains an Account name and Account type. •  Note, the Account object does NOT contain a password •  Example: user has multiple twitter accountsv AccountManager maps an Account object to it’s “password”v Recommended strategy: store Account and authToken on device •  SampleSyncAdapter project stores password (possible human error)v SyncManager can only schedule syncs per Account
  31. 31. ACCOUNT MANAGERv Contains centralized registry of user’s online accountsv Used to determine list of data sources to be synced •  AccountManager provides list of Accounts •  SyncManager grabs the list of Accounts for syncingv AccountAuthenticatorCache maps accountType to objectsextending AbstractAccountAuthenticatorv Android Component; you don’t write this
  32. 32. AUTHENTICATIONv User chooses to Add an Account •  List compiled from array of allowable account typesv System chooses Authenticator based on“android:accountType” •  Binds to a Service which returns the Authenticator’s IBinderv Authenticator’s overridden addAccount() method is called •  Ultimately the Login UI displays, new Account is created
  33. 33. AUTHENTICATORv Allows developer to implement authentication •  Per remote servicev Must extend AbstractAccountAuthenticator •  Responds to an intent “android.accounts.AccountAuthenticator” advertised by the AccountManager for it’s accountType only.v Authentication Service returns a Binder to your implementedAbstractAccountAuthenticatorv addAccount() returns bundle with intent containing Activity
  34. 34. ADD ACCOUNTSample SyncAdapter Activity Example Activity
  35. 35. A Primer to SyncAdaptersTHE SYNC
  36. 36. SYNCMANAGERv Responsible for scheduling, cancelling syncs. •  Maintains a list of active syncs (mActiveSyncContext)v Sync handling strategy very tightly coupled to Accounts •  Account is part of most SyncManager methodsv How do the SyncHandler and Account interact? •  SyncHandler receives a message containing an ActiveSyncContext. ActiveSyncContext contains all information about the sync that needs to begin including the Account.
  37. 37. SYNCHRONIZATIONv SyncManager contains ONE SyncHandlerv SyncHandler’s job: receive/handle sync operation messages •  On receiving a Connection Message, calls startSync for the syncAdapter in question •  startSync() spins up a new SyncThread •  The method onPerformSync() that was implemented is invoked when run() is invoked on the thread
  38. 38. SYNC ADAPTERv Where the main party happens. The method onPerformSync()gets called within a Make use of the DIRTY/VERSION/SOURCE_ID rowsv Instantiate like any class. •  However, create only one for thread safety.
  39. 39. ONPERFORMSYNC()v What should I do in the onPerformSync() method?v Merge remote data with local data •  DIRTY/VERSION/SOURCE_ID columnsv Use business rules to determine order of operations •  Whether local data overwrites remote data or vice versav Implement a remote connection strategy to access remotedata
  40. 40. DEV TOOLS
  41. 41. WRAP UPv We learned… •  What SyncAdapters are •  Set up •  Content (ContentProvider/data characteristics) •  Authorization (Accounts, Account Management) •  Synchronization (SyncManager, SyncService) •  Debugging/Dev Tools
  42. 42. A Primer to SyncAdaptersQUESTIONS?