SlideShare une entreprise Scribd logo
1  sur  47
A PRIMER TO
SYNC ADAPTERS
AnDevCon V - Boston
May 2013
Kiana Tennyson
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
Kiana
@kiaaaana
Software developer,
Manheim
Blank App Project
blankapp.blogspot.com
What’s a Sync Adapter?
•  Transfers data to/from Android phone to remote data
source
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
Good News!
• Writing a Custom Sync
Adapter is actually
pretty easy!
Sad News…
• You will have to
implement business
rules…
•  Authentication Handling
•  (Custom) Content Provider
•  Data Handling
Good Use Cases
•  Requires Authentication Step
to connect to remote DS
•  Has a Custom Content
Provider
•  Will require a new Sync Adapter
•  Application Suite backed by a
Custom ContentProvider
•  Requires non-authentication
permissions
(Bad?) Use Cases
•  Does not require permissions or
login
•  RSS/public data feed
•  Write a parser the reads the feed
upon user need (poetry)
•  Sync Adapter not necessary to
write to a ContentProvider
•  If Service does not need to
constantly run in background
•  Conserve battery power, or user will
delete your app
The Big Picture
AccountManager
• Requires
Authentication
Service to add
Account
• Adds Account to
Account List
SyncManager
• Uses Account
List as a basis
for it’s Sync List
• Requires Sync
Service to start
data syncs
ContentProvider
•  Holds the data
•  Called in
onPerformSync()
CONFIGURATION
How do I set this thing up?
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
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
Synchronization & Authentication
Resource XMLs
•  Provide configuration info
•  Map account type to objects
•  SyncAdapter and Authenticator are connected via
android:accountType
•  Map content authority to SyncAdapter
Resource XMLs
AccountAuthenticator
!
<?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"!
/>!
AddAccount
•  Notice result of android:icon
•  Green lights – Account added
•  Gray lights – Account not
added
•  Clicking one launches Auth
Activity interface
Resource XMLs
SyncAdapter
!
<?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"!
/>!
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)
Manifest Example
<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>!
Why Services?
•  Why do we need these <service> tags?
•  SyncAdapter is bound to a service, Authentication is bound to a
service… 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
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?
THE DATA
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
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 remote
source
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 Custom
SyncAdapter
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 transmitted
data?
•  Likely defined by business limitations.
•  How does the device parse/save the data?
•  ContentProviderClient or ContentResolver (batch ops)
Android SampleSyncAdapter
•  ContentProviderClient
•  in onPerformSync() method signature
•  Unused!
•  ContentResolver
•  Performs actual syncing
in NetworkUtilities.java
Accessing Content
The Device User
Android Application(s)
Context
ContentResolver
ContentProviderClient
ContentProvider
Data Storage
•  SharedPreferences
•  External Storage
•  SQLLiteDatabase
A Comparison
Content Resolver
•  Thread safe
•  Many calls to many
ContentAuthorities (CA)
•  Expensive call
(Many CA lookups)
•  Resolver contains a Client
ContentProviderClient
•  Not thread safe
•  Repeated calls to same
CA
•  Cheaper call (one CA
lookup)
•  You MUST call release()
to avoid memory leak
AUTHENTICATION
Account
•  Account object contains an Account name and Account
type.
•  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 on
device
•  SampleSyncAdapter project stores password (possible human
error)
•  SyncManager can only schedule syncs per Account
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 objects
extending AbstractAccountAuthenticator
•  Android Component; you don’t write this
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
Add Account
Sample SyncAdapter Activity Example Activity
SYNCHRONIZATION
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 an
ActiveSyncContext. ActiveSyncContext contains all information
about the sync that needs to begin including the Account.
Synchronization
•  SyncManager contains ONE SyncHandler
•  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
SyncAdapter
•  Where the main party happens. The method
onPerformSync() 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.
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 remote
data
PREFERENCES
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?
Resource XMLs
AccountAuthenticator
!
<?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”!
/>!
DevTools
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
QUESTIONS?
A Primer to SyncAdapters

Contenu connexe

Tendances

Build Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesBuild Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesAmazon Web Services
 
Microsoft Graph developer community call-March 2020
Microsoft Graph developer community call-March 2020Microsoft Graph developer community call-March 2020
Microsoft Graph developer community call-March 2020Microsoft 365 Developer
 
Build Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesBuild Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesAmazon Web Services
 
R.A.P. (Rely on Android Platform)
R.A.P. (Rely on Android Platform)R.A.P. (Rely on Android Platform)
R.A.P. (Rely on Android Platform)Aditium
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controlsRaed Aldahdooh
 
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...Amazon Web Services
 
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014Amazon Web Services
 
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...Using Windows Azure for Solving Identity Management Challenges (Visual Studio...
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...Michael Collier
 
Inside the Android AccountManager
Inside the Android AccountManagerInside the Android AccountManager
Inside the Android AccountManagerSamael Wang
 
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...Amazon Web Services
 
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...Amazon Web Services
 
Building Mobile Apps on AWS at Websummit Diublin
Building Mobile Apps on AWS at Websummit DiublinBuilding Mobile Apps on AWS at Websummit Diublin
Building Mobile Apps on AWS at Websummit DiublinAmazon Web Services
 
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB
 
Implement Authorization in your Apps with Microsoft identity platform-June 2020
Implement Authorization in your Apps with Microsoft identity platform-June 2020Implement Authorization in your Apps with Microsoft identity platform-June 2020
Implement Authorization in your Apps with Microsoft identity platform-June 2020Microsoft 365 Developer
 
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...Amazon Web Services
 
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...Amazon Web Services
 
Salesforce Lightning Tips & Tricks
Salesforce Lightning Tips & Tricks Salesforce Lightning Tips & Tricks
Salesforce Lightning Tips & Tricks Thinqloud
 
Cloud-powered Cross-platform Mobile Apps on AWS
Cloud-powered Cross-platform Mobile Apps on AWSCloud-powered Cross-platform Mobile Apps on AWS
Cloud-powered Cross-platform Mobile Apps on AWSDanilo Poccia
 

Tendances (20)

Build Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesBuild Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile Services
 
Microsoft Graph developer community call-March 2020
Microsoft Graph developer community call-March 2020Microsoft Graph developer community call-March 2020
Microsoft Graph developer community call-March 2020
 
Build Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile ServicesBuild Your Mobile App Faster with AWS Mobile Services
Build Your Mobile App Faster with AWS Mobile Services
 
R.A.P. (Rely on Android Platform)
R.A.P. (Rely on Android Platform)R.A.P. (Rely on Android Platform)
R.A.P. (Rely on Android Platform)
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controls
 
Building mobile apps on AWS
Building mobile apps on AWSBuilding mobile apps on AWS
Building mobile apps on AWS
 
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...
(MBL311) Workshop: Build an Android App Using AWS Mobile Services | AWS re:In...
 
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014
(MBL310) Workshop: Build iOS Apps Using AWS Mobile Services | AWS re:Invent 2014
 
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...Using Windows Azure for Solving Identity Management Challenges (Visual Studio...
Using Windows Azure for Solving Identity Management Challenges (Visual Studio...
 
Inside the Android AccountManager
Inside the Android AccountManagerInside the Android AccountManager
Inside the Android AccountManager
 
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...
AWS Mobile Services: Amazon Cognito - Identity Broker and Synchronization Ser...
 
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...
Getting Started with your User Pools in Amazon Cognito - AWS June 2016 Webina...
 
Amazon Cognito
Amazon CognitoAmazon Cognito
Amazon Cognito
 
Building Mobile Apps on AWS at Websummit Diublin
Building Mobile Apps on AWS at Websummit DiublinBuilding Mobile Apps on AWS at Websummit Diublin
Building Mobile Apps on AWS at Websummit Diublin
 
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
 
Implement Authorization in your Apps with Microsoft identity platform-June 2020
Implement Authorization in your Apps with Microsoft identity platform-June 2020Implement Authorization in your Apps with Microsoft identity platform-June 2020
Implement Authorization in your Apps with Microsoft identity platform-June 2020
 
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
 
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...
Serverless Patterns: “No server is easier to manage than no server” - AWS Sec...
 
Salesforce Lightning Tips & Tricks
Salesforce Lightning Tips & Tricks Salesforce Lightning Tips & Tricks
Salesforce Lightning Tips & Tricks
 
Cloud-powered Cross-platform Mobile Apps on AWS
Cloud-powered Cross-platform Mobile Apps on AWSCloud-powered Cross-platform Mobile Apps on AWS
Cloud-powered Cross-platform Mobile Apps on AWS
 

Similaire à AnDevCon - A Primer to Sync Adapters

O365Con18 - Hybrid SharePoint Deep Dive - Thomas Vochten
O365Con18 - Hybrid SharePoint Deep Dive - Thomas VochtenO365Con18 - Hybrid SharePoint Deep Dive - Thomas Vochten
O365Con18 - Hybrid SharePoint Deep Dive - Thomas VochtenNCCOMMS
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncmdevtalk
 
Identity Management in SharePoint 2013
Identity Management in SharePoint 2013Identity Management in SharePoint 2013
Identity Management in SharePoint 2013SPC Adriatics
 
Patterns of Distributed Application Design
Patterns of Distributed Application DesignPatterns of Distributed Application Design
Patterns of Distributed Application DesignOrkhan Gasimov
 
Tech Talk on Cloud Computing
Tech Talk on Cloud ComputingTech Talk on Cloud Computing
Tech Talk on Cloud ComputingITviec
 
Exploring Contact Lens and Amazon Connect
Exploring Contact Lens and Amazon ConnectExploring Contact Lens and Amazon Connect
Exploring Contact Lens and Amazon ConnectCloudHesive
 
Portal and Intranets
Portal and Intranets Portal and Intranets
Portal and Intranets Redar Ismail
 
2014-05-17 SPS Baltimore - Worst Practices of SharePoint
2014-05-17 SPS Baltimore - Worst Practices of SharePoint2014-05-17 SPS Baltimore - Worst Practices of SharePoint
2014-05-17 SPS Baltimore - Worst Practices of SharePointDan Usher
 
Developing a provider hosted share point app
Developing a provider hosted share point appDeveloping a provider hosted share point app
Developing a provider hosted share point appTalbott Crowell
 
BDA307 Real-time Streaming Applications on AWS, Patterns and Use Cases
BDA307 Real-time Streaming Applications on AWS, Patterns and Use CasesBDA307 Real-time Streaming Applications on AWS, Patterns and Use Cases
BDA307 Real-time Streaming Applications on AWS, Patterns and Use CasesAmazon Web Services
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2Jaliya Udagedara
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationNordic APIs
 
2016-06 - Design your api management strategy - AWS - Microservices on AWS
2016-06 - Design your api management strategy - AWS - Microservices on AWS2016-06 - Design your api management strategy - AWS - Microservices on AWS
2016-06 - Design your api management strategy - AWS - Microservices on AWSSmartWave
 
Aws organizations
Aws organizationsAws organizations
Aws organizationsOlaf Conijn
 
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraphVincent Biret
 
SharePoint 2013 APIs demystified
SharePoint 2013 APIs demystifiedSharePoint 2013 APIs demystified
SharePoint 2013 APIs demystifiedSPC Adriatics
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationJerod Johnson
 
ENT302 Deep Dive on AWS Management Tools and New Launches
ENT302 Deep Dive on AWS Management Tools and New LaunchesENT302 Deep Dive on AWS Management Tools and New Launches
ENT302 Deep Dive on AWS Management Tools and New LaunchesAmazon Web Services
 

Similaire à AnDevCon - A Primer to Sync Adapters (20)

O365Con18 - Hybrid SharePoint Deep Dive - Thomas Vochten
O365Con18 - Hybrid SharePoint Deep Dive - Thomas VochtenO365Con18 - Hybrid SharePoint Deep Dive - Thomas Vochten
O365Con18 - Hybrid SharePoint Deep Dive - Thomas Vochten
 
Fire up your mobile app!
Fire up your mobile app!Fire up your mobile app!
Fire up your mobile app!
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & sync
 
Identity Management in SharePoint 2013
Identity Management in SharePoint 2013Identity Management in SharePoint 2013
Identity Management in SharePoint 2013
 
Patterns of Distributed Application Design
Patterns of Distributed Application DesignPatterns of Distributed Application Design
Patterns of Distributed Application Design
 
Tech Talk on Cloud Computing
Tech Talk on Cloud ComputingTech Talk on Cloud Computing
Tech Talk on Cloud Computing
 
Exploring Contact Lens and Amazon Connect
Exploring Contact Lens and Amazon ConnectExploring Contact Lens and Amazon Connect
Exploring Contact Lens and Amazon Connect
 
Portal and Intranets
Portal and Intranets Portal and Intranets
Portal and Intranets
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
2014-05-17 SPS Baltimore - Worst Practices of SharePoint
2014-05-17 SPS Baltimore - Worst Practices of SharePoint2014-05-17 SPS Baltimore - Worst Practices of SharePoint
2014-05-17 SPS Baltimore - Worst Practices of SharePoint
 
Developing a provider hosted share point app
Developing a provider hosted share point appDeveloping a provider hosted share point app
Developing a provider hosted share point app
 
BDA307 Real-time Streaming Applications on AWS, Patterns and Use Cases
BDA307 Real-time Streaming Applications on AWS, Patterns and Use CasesBDA307 Real-time Streaming Applications on AWS, Patterns and Use Cases
BDA307 Real-time Streaming Applications on AWS, Patterns and Use Cases
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
2016-06 - Design your api management strategy - AWS - Microservices on AWS
2016-06 - Design your api management strategy - AWS - Microservices on AWS2016-06 - Design your api management strategy - AWS - Microservices on AWS
2016-06 - Design your api management strategy - AWS - Microservices on AWS
 
Aws organizations
Aws organizationsAws organizations
Aws organizations
 
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph
#Techorama belgium 2018 vincent biret deep dive with the #MicrosoftGraph
 
SharePoint 2013 APIs demystified
SharePoint 2013 APIs demystifiedSharePoint 2013 APIs demystified
SharePoint 2013 APIs demystified
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
ENT302 Deep Dive on AWS Management Tools and New Launches
ENT302 Deep Dive on AWS Management Tools and New LaunchesENT302 Deep Dive on AWS Management Tools and New Launches
ENT302 Deep Dive on AWS Management Tools and New Launches
 

AnDevCon - A Primer to Sync Adapters

  • 1. A PRIMER TO SYNC ADAPTERS AnDevCon V - Boston May 2013 Kiana 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
  • 4. What’s a Sync Adapter? •  Transfers data to/from Android phone to remote data source
  • 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 Sync Adapter is actually pretty easy!
  • 7. Sad News… • You will have to implement business rules… •  Authentication Handling •  (Custom) Content Provider •  Data Handling
  • 8. Good Use Cases •  Requires Authentication Step to connect to remote DS •  Has a Custom Content Provider •  Will require a new Sync Adapter •  Application Suite backed by a Custom ContentProvider •  Requires non-authentication permissions
  • 9. (Bad?) Use Cases •  Does not require permissions or login •  RSS/public data feed •  Write a parser the reads the feed upon user need (poetry) •  Sync Adapter not necessary to write to a ContentProvider •  If Service does not need to constantly run in background •  Conserve battery power, or user will delete your app
  • 10. The Big Picture AccountManager • Requires Authentication Service to add Account • Adds Account to Account List SyncManager • Uses Account List as a basis for it’s Sync List • Requires Sync Service to start data syncs ContentProvider •  Holds the data •  Called in onPerformSync()
  • 11. CONFIGURATION How 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
  • 15. Resource XMLs •  Provide configuration info •  Map account type to objects •  SyncAdapter and Authenticator are connected via android:accountType •  Map content authority to SyncAdapter
  • 16. Resource XMLs AccountAuthenticator ! <?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 not added •  Clicking one launches Auth Activity interface
  • 18. Resource XMLs SyncAdapter ! <?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>! <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>!
  • 21. Why Services? •  Why do we need these <service> tags? •  SyncAdapter is bound to a service, Authentication is bound to a service… 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.
  • 25. 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
  • 26. 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 remote source
  • 27. 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 Custom SyncAdapter
  • 28. 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 transmitted data? •  Likely defined by business limitations. •  How does the device parse/save the data? •  ContentProviderClient or ContentResolver (batch ops)
  • 29. Android SampleSyncAdapter •  ContentProviderClient •  in onPerformSync() method signature •  Unused! •  ContentResolver •  Performs actual syncing in NetworkUtilities.java
  • 30. Accessing Content The Device User Android Application(s) Context ContentResolver ContentProviderClient ContentProvider Data Storage •  SharedPreferences •  External Storage •  SQLLiteDatabase
  • 31. A Comparison Content Resolver •  Thread safe •  Many calls to many ContentAuthorities (CA) •  Expensive call (Many CA lookups) •  Resolver contains a Client ContentProviderClient •  Not thread safe •  Repeated calls to same CA •  Cheaper call (one CA lookup) •  You MUST call release() to avoid memory leak
  • 33. Account •  Account object contains an Account name and Account type. •  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 on device •  SampleSyncAdapter project stores password (possible human error) •  SyncManager can only schedule syncs per Account
  • 34. 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 objects extending AbstractAccountAuthenticator •  Android Component; you don’t write this
  • 35. 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
  • 36. Add Account Sample SyncAdapter Activity Example Activity
  • 38. 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 an ActiveSyncContext. ActiveSyncContext contains all information about the sync that needs to begin including the Account.
  • 39. Synchronization •  SyncManager contains ONE SyncHandler •  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
  • 40. SyncAdapter •  Where the main party happens. The method onPerformSync() 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.
  • 41. 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 remote data
  • 43. 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?
  • 44. Resource XMLs AccountAuthenticator ! <?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”! />!
  • 46. 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
  • 47. QUESTIONS? A Primer to SyncAdapters