Your SlideShare is downloading. ×
AnDevCon - A Primer to Sync Adapters
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

AnDevCon - A Primer to Sync Adapters

2,368
views

Published on


0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,368
On Slideshare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
0
Comments
0
Likes
6
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. A PRIMER TOSYNC ADAPTERSAnDevCon V - BostonMay 2013Kiana Tennyson
  • 2. Overview•  Who am I?•  What’s a Sync Adapter•  Use Cases•  The Big Picture•  Configuration•  Authorization, Content, Synchronization•  Options/User Preferences•  Debugging•  Wrap up/Questions
  • 3. Kiana@kiaaaanaSoftware developer,ManheimBlank App Projectblankapp.blogspot.com
  • 4. What’s a Sync Adapter?•  Transfers data to/from Android phone to remote datasource
  • 5. What’s a Sync Adapter?•  Plug-in Architecture•  Coordinates Network Availability with syncing•  Gracefully handles Network Interruptions•  Schedules synchronization•  Handles stopped processes•  Accommodates user preferences
  • 6. Good News!• Writing a Custom SyncAdapter is actuallypretty easy!
  • 7. Sad News…• You will have toimplement businessrules…•  Authentication Handling•  (Custom) Content Provider•  Data Handling
  • 8. Good Use Cases•  Requires Authentication Stepto connect to remote DS•  Has a Custom ContentProvider•  Will require a new Sync Adapter•  Application Suite backed by aCustom ContentProvider•  Requires non-authenticationpermissions
  • 9. (Bad?) Use Cases•  Does not require permissions orlogin•  RSS/public data feed•  Write a parser the reads the feedupon user need (poetry)•  Sync Adapter not necessary towrite to a ContentProvider•  If Service does not need toconstantly run in background•  Conserve battery power, or user willdelete your app
  • 10. The Big PictureAccountManager• RequiresAuthenticationService to addAccount• Adds Account toAccount ListSyncManager• Uses AccountList as a basisfor it’s Sync List• Requires SyncService to startdata syncsContentProvider•  Holds the data•  Called inonPerformSync()
  • 11. CONFIGURATIONHow do I set this thing up?
  • 12. Authentication•  Write an AuthActivity•  serves UI for user to enter account info•  Write it to complete the authorization process•  Write an Authenticator•  MUST extend AbstractAccountAuthenticator•  Returns the AuthActivity in a Bundle object•  Write an Authentication Service•  MUST extend Service•  onBind return IBinder for the Authenticator
  • 13. Synchronization•  Write a SyncAdapter•  MUST extend AbstractThreadedSyncAdapter•  Overwrite onPerformSync()•  Write a Sync Service•  MUST extend Service•  Allow creation of ONE SyncAdapter•  onBind returns a IBinder for SyncAdapter
  • 14. Synchronization & Authentication
  • 15. Resource XMLs•  Provide configuration info•  Map account type to objects•  SyncAdapter and Authenticator are connected viaandroid:accountType•  Map content authority to SyncAdapter
  • 16. Resource XMLsAccountAuthenticator!<?xml version="1.0" encoding="utf-8"?>!<account-authenticator !xmlns:android="http://schemas.android.com/apk/res/! !android”!!android:accountType=”your.uniquename.here"!!android:icon="@drawable/icon"!!android:smallIcon="@drawable/icon"!!android:label="@string/label"!/>!
  • 17. AddAccount•  Notice result of android:icon•  Green lights – Account added•  Gray lights – Account notadded•  Clicking one launches AuthActivity interface
  • 18. Resource XMLsSyncAdapter!<?xml version="1.0" encoding="utf-8"?>!<sync-adapter!xmlns:android="http://schemas.android.com/apk/res/!android”!android:contentAuthority="com.android.contacts"!android:accountType="your.uniquename.here"!android:supportsUploading="false"!android:userVisible="true"!/>!
  • 19. Manifest•  Include several appropriate permissions•  Declare AuthenticationService with <service> tag•  Intent filter: “android.accounts.AccountAuthenticator”•  Meta-data tag points AccountAuthenticator to xml resource file•  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-types•  Declare AuthActivity (no Intent filter necessary)
  • 20. Manifest Example<service android:name=".authenticator.AuthenticationService”!android:exported="true”>!<intent-filter>!<actionandroid: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>!
  • 21. Why Services?•  Why do we need these <service> tags?•  SyncAdapter is bound to a service, Authentication is bound to aservice… but why?•  SyncManager finds all syncAdapters via a SyncAdaptersCache•  AccountManager finds all Accounts via AccountAuthenticatorCache•  RegisteredServicesCache•  Reads the XML files created (account-authenticator and syncadapter)•  Generates service maps
  • 22. Code Summary•  Create a syncadapter.xml file•  Create an authenticator.xml file•  Add an authentication <service> to manifest•  Add a sync <service> to manifest•  Add correct permissions to manifest•  Write some java… but what does any of this mean?
  • 23. THE DATA
  • 24. Content Provider•  Manages central repository of data.•  SyncAdapters wouldn’t exist without ContentProviders•  SyncAdapter mentioned in ContentProvider section of API Guide•  Built in ContentProviders contain a SyncState table•  Use to store sync state, meta-data or any sync related data•  Sync related columns in other tables:•  DIRTY, VERSION, SOURCE_ID
  • 25. Important Columns•  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 URI•  VERSION•  Incremented by Provider whenever the data row is changed.•  High-water marking (aka lastSyncState)•  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 remotesource
  • 26. Custom Content Provider•  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 essential•  These properties should be applied to CustomSyncAdapter
  • 27. Data Considerations•  Determine structure of serialized/transmitted data•  Using json? xml? yaml?•  What does a single row (data unit) look like?•  How does the server parse and save the transmitteddata?•  Likely defined by business limitations.•  How does the device parse/save the data?•  ContentProviderClient or ContentResolver (batch ops)
  • 28. Android SampleSyncAdapter•  ContentProviderClient•  in onPerformSync() method signature•  Unused!•  ContentResolver•  Performs actual syncingin NetworkUtilities.java
  • 29. Accessing ContentThe Device UserAndroid Application(s)ContextContentResolverContentProviderClientContentProviderData Storage•  SharedPreferences•  External Storage•  SQLLiteDatabase
  • 30. A ComparisonContent Resolver•  Thread safe•  Many calls to manyContentAuthorities (CA)•  Expensive call(Many CA lookups)•  Resolver contains a ClientContentProviderClient•  Not thread safe•  Repeated calls to sameCA•  Cheaper call (one CAlookup)•  You MUST call release()to avoid memory leak
  • 31. AUTHENTICATION
  • 32. Account•  Account object contains an Account name and Accounttype.•  Note, the Account object does NOT contain a password•  Example: user has multiple twitter accounts•  AccountManager maps an Account object to it’s“password”•  Recommended strategy: store Account and authToken ondevice•  SampleSyncAdapter project stores password (possible humanerror)•  SyncManager can only schedule syncs per Account
  • 33. Account Manager•  Contains centralized registry of user’s online accounts•  Used to determine list of data sources to be synced•  AccountManager provides list of Accounts•  SyncManager grabs the list of Accounts for syncing•  AccountAuthenticatorCache maps accountType to objectsextending AbstractAccountAuthenticator•  Android Component; you don’t write this
  • 34. Authentication•  User chooses to Add an Account•  List compiled from array of allowable account types•  System chooses Authenticator based on“android:accountType”•  Binds to a Service which returns the Authenticator’s IBinder•  Authenticator’s overridden addAccount() method is called•  Ultimately the Login UI displays, new Account is created
  • 35. Add AccountSample SyncAdapter Activity Example Activity
  • 36. SYNCHRONIZATION
  • 37. SyncManager•  Responsible for scheduling, cancelling syncs.•  Maintains a list of active syncs (mActiveSyncContext)•  Sync handling strategy very tightly coupled to Accounts•  Account is part of most SyncManager methods•  How do the SyncHandler and Account interact?•  SyncHandler receives a message containing anActiveSyncContext. ActiveSyncContext contains all informationabout the sync that needs to begin including the Account.
  • 38. Synchronization•  SyncManager contains ONE SyncHandler•  SyncHandler’s job: receive/handle sync operationmessages•  On receiving a Connection Message, calls startSync for thesyncAdapter in question•  startSync() spins up a new SyncThread•  The method onPerformSync() that was implemented is invokedwhen run() is invoked on the thread
  • 39. SyncAdapter•  Where the main party happens. The methodonPerformSync() gets called within a syncThread.run()•  Make use of the DIRTY/VERSION/SOURCE_ID rows•  Instantiate like any class.•  However, create only one for thread safety.
  • 40. onPerformSync()•  What should I do in the onPerformSync() method?•  Merge remote data with local data•  DIRTY/VERSION/SOURCE_ID columns•  Use business rules to determine order of operations•  Whether local data overwrites remote data or vice versa•  Implement a remote connection strategy to access remotedata
  • 41. PREFERENCES
  • 42. User Preferences•  Intended for use with Preferences Framework•  Add “android:accountPreferences” to<account-authenticator>•  Build Preferences resource file•  Create Activity which gathers user prefs•  Must extend PreferenceActivity•  Noticing a pattern?
  • 43. Resource XMLsAccountAuthenticator!<?xml version="1.0" encoding="utf-8"?>!<account-authenticator !xmlns:android="http://schemas.android.com/apk/res/! !android”!!android:accountType=”your.uniquename.here"!!android:icon="@drawable/icon"!!android:smallIcon="@drawable/icon"!!android:label="@string/label”!!android:accountPreferences=“@xml/acct_prefs”!/>!
  • 44. DevTools
  • 45. Wrap Up•  We learned…•  What SyncAdapters are•  Set up•  Content (ContentProvider/data characteristics)•  Authorization (Accounts, Account Management)•  Synchronization (SyncManager, SyncService)•  User Preferences•  Debugging/Dev Tools
  • 46. QUESTIONS?A Primer to SyncAdapters