概述
在sdk目錄下有個示例項目SampleSyncAdapter,演示了 用戶授權和同步適配器的一些內容,是個學習的很好范例。我讀了很久,很多地方?jīng)]搞明白,先把理解的一些記錄下來。
通過學習該示例,你可以做到:
自定義的賬戶,讓你的賬戶出現(xiàn)在 安卓系統(tǒng)設置的“賬戶”分組下。我看了下,像googel,華為,微信,支付寶都在這里出現(xiàn)。
定義同步的適配器。這里我還沒搞明白,似乎需要自定義contentProvider,到底什么時候會觸發(fā)同步(同步頻率控制),如何手動觸發(fā),等等,我還沒搞懂
我的理解
下面是我理解的代碼里的一些class的作用:
authenticator包
AuthenticationService 繼承自Service,認證服務
拿Authenticator作為成員,在onBind時返回mAuthenticator.getIBinder()
Authenticator 繼承AbstractAccountAuthenticator 驗證器
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,String authTokenType,
String[] requiredFeatures, Bundle options)
添加賬戶。返回一個intent,this intent 用于啟動 登錄頁。
public Bundle getAuthToken(AccountAuthenticatorResponse response,
Account account,String authTokenType, Bundle loginOptions)
獲得 authToken。先從賬戶管理器里取密碼,
如果能得到密碼,則將賬戶密碼使用NetworkUtilities.authenticate以獲得authToken
如果未得到,則將用戶名和賬戶類型發(fā)送到 登錄頁,以再次認證。
AuthenticatorActivity ,繼承自 AccountAuthenticatorActivity
登錄頁,顯示用戶名和密碼輸入框,等待用戶輸入。點擊登錄按鈕后觸發(fā)handleLogin事件,
在這里先驗證用戶輸入非空,啟動UserLoginTask。
在doInBackground中調用NetworkUtilities.authenticate獲得authToken,
完成后保存用戶名和密碼。
client包
NetworkUtilities:
public static String authenticate(String username, String password)
發(fā)送用戶名和密碼到服務端,收到 authToken字符串
public static List<RawContact> syncContacts(
Account account, String authtoken, long serverSyncState,
List<RawContact> dirtyContacts)
發(fā)送 用戶名和authToken,serverSyncState, 和一個 聯(lián)系人集合到服務端,
收到一個聯(lián)系人集合
public static byte[] downloadAvatar(final String avatarUrl)
通過一個URL,獲得用戶頭像的 字節(jié)集合
RawContact:
聯(lián)系人信息的實體bean
notifier包
NotifierService: 通知服務,Service to handle view notifications.
This allows the sample sync adapter to update the information
when the contact is being looked at syncadapter
syncadapter包
SyncAdapter:同步服務,繼承自AbstractThreadedSyncAdapter
public void onPerformSync(Account account, Bundle extras,
String authority,ContentProviderClient provider, SyncResult syncResult)
處理同步,獲得同步標記,獲得需要同步的聯(lián)系人,更新聯(lián)系人,保存同步標記
SyncService:繼承自Service
拿SyncAdapter作為成員,在onBind時返回 sSyncAdapter.getSyncAdapterBinder()
Constants 常量,聲明 賬戶類型ACCOUNT_TYPE,授權標記類型AUTHTOKEN_TYPE
AccountManager的常用方法
為指定賬戶設定密碼
mAccountManager.setPassword(account, mPassword);
添加賬戶到 賬戶中心
final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
mAccountManager.addAccountExplicitly(account, mPassword, null);
獲得authToken
final String authtoken = mAccountManager.blockingGetAuthToken(account,
Constants.AUTHTOKEN_TYPE, NOTIFY_AUTH_FAILURE);
獲得用戶數(shù)據(jù)
String markerString = mAccountManager.getUserData(account, SYNC_MARKER_KEY);
參考:
http://yarin.blog.51cto.com/1130898/479032/
http://www.cnblogs.com/fengzhblog/p/3177002.html
http://blog.csdn.net/wutianyin222/article/details/7911858
http://mobile.51cto.com/aprogram-392392.htm
http://mobile.51cto.com/aprogram-392388.htm