裝過Android版的Facebook、lastfm的同學(xué)是否對于這些應(yīng)用的功能感到驚喜,它們可以定期更新朋友的最新信息,將最新近況和心情短語集成入聯(lián)系人中。這些應(yīng)用全部是以Android2.0后的賬戶和同步機(jī)制為基礎(chǔ)的。Google的例程中給出了名為SampleSyncAdpater的例子,通過分析該例子可以學(xué)會Android中的Account驗(yàn)證、同步Adapter的使用。
詳細(xì)例子代碼可以看sdk samples中提供的源碼,現(xiàn)在拿2.2中的版本來簡要說明。
首先是 class Authenticator extends AbstractAccountAuthenticator ,該類是賬戶認(rèn)證類,打開手機(jī)的Setting里,有Account&Sync 一項(xiàng),Authenticator就是實(shí)現(xiàn)其中的賬號功能的類。
-
- public Bundle addAccount(AccountAuthenticatorResponse response,
- String accountType, String authTokenType, String[] requiredFeatures,
- Bundle options) {
- final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
- intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE,
- authTokenType);
- intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
- response);
- final Bundle bundle = new Bundle();
- bundle.putParcelable(AccountManager.KEY_INTENT, intent);
- return bundle;
- }
其中addAccount方法用來定義需要增加賬號時的操作,如調(diào)用AuthenticatorActivity來進(jìn)行賬號的添加認(rèn)證。
在AuthenticatorActivity.java中定義了handleLogin(),此方法由login_activity.xml中的android:onClick="handleLogin"定義與ui中的okbutton的關(guān)聯(lián)。
-
- <Button
- android:id="@+id/ok_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:minWidth="100dip"
- android:text="@string/login_activity_ok_button"
- android:onClick="handleLogin" />
handleLogin()將ui中的用戶名和密碼取得,并創(chuàng)建一個試圖認(rèn)證的線程,通過網(wǎng)絡(luò)去服務(wù)端驗(yàn)證。
NetworkUtilities.java中的 public static boolean authenticate(String username, String password, Handler handler, final Context context)方法展示了通過網(wǎng)絡(luò)驗(yàn)證的具體流程。得到服務(wù)端驗(yàn)證結(jié)果后,在sendResult()中通過handler.post調(diào)用來實(shí)現(xiàn)onAuthenticationResult()在AuthenticatorActivity中的運(yùn)行。onAuthenticationResult()判斷驗(yàn)證通過則結(jié)束AuthenticatorActivity,否則報(bào)出用戶名密碼錯,讓用戶在AuthenticatorActivity中再次嘗試驗(yàn)證。
-
-
-
-
-
-
-
- public void handleLogin(View view) {
- if (mRequestNewAccount) {
- mUsername = mUsernameEdit.getText().toString();
- }
- mPassword = mPasswordEdit.getText().toString();
- if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
- mMessage.setText(getMessage());
- } else {
- showProgress();
-
- mAuthThread =
- NetworkUtilities.attemptAuth(mUsername, mPassword, mHandler,
- AuthenticatorActivity.this);
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static boolean authenticate(String username, String password,
- Handler handler, final Context context) {
- final HttpResponse resp;
-
- final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair(PARAM_USERNAME, username));
- params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
- HttpEntity entity = null;
- try {
- entity = new UrlEncodedFormEntity(params);
- } catch (final UnsupportedEncodingException e) {
-
- throw new AssertionError(e);
- }
- final HttpPost post = new HttpPost(AUTH_URI);
- post.addHeader(entity.getContentType());
- post.setEntity(entity);
- maybeCreateHttpClient();
-
- try {
- resp = mHttpClient.execute(post);
- if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "Successful authentication");
- }
- sendResult(true, handler, context);
- return true;
- } else {
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "Error authenticating" + resp.getStatusLine());
- }
- sendResult(false, handler, context);
- return false;
- }
- } catch (final IOException e) {
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "IOException when getting authtoken", e);
- }
- sendResult(false, handler, context);
- return false;
- } finally {
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "getAuthtoken completing");
- }
- }
- }
-
-
-
-
-
-
-
-
-
- private static void sendResult(final Boolean result, final Handler handler,
- final Context context) {
- if (handler == null || context == null) {
- return;
- }
- handler.post(new Runnable() {
- public void run() {
- ((AuthenticatorActivity) context).onAuthenticationResult(result);
- }
- });
- }
-
-
-
-
- public void onAuthenticationResult(boolean result) {
- Log.i(TAG, "onAuthenticationResult(" + result + ")");
-
- hideProgress();
- if (result) {
- if (!mConfirmCredentials) {
- finishLogin();
- } else {
- finishConfirmCredentials(true);
- }
- } else {
- Log.e(TAG, "onAuthenticationResult: failed to authenticate");
- (mRequestNewAccount) {
-
- mMessage
- .setText(getText(R.string.login_activity_loginfail_text_both));
- } else {
-
-
-
- mMessage
- .setText(getText(R.string.login_activity_loginfail_text_pwonly));
- }
- }
- }
Account的驗(yàn)證完畢后,就生成了賬號,可以開始使用同步功能了。同步的主要邏輯在public class SyncAdapter extends AbstractThreadedSyncAdapter中實(shí)現(xiàn)。
-
- @Override
- public void onPerformSync(Account account, Bundle extras, String authority,
- ContentProviderClient provider, SyncResult syncResult) {
- List<User> users;
- List<Status> statuses;
- String authtoken = null;
- try {
-
- authtoken =
- mAccountManager.blockingGetAuthToken(account,
- Constants.AUTHTOKEN_TYPE, true );
-
- users =
- NetworkUtilities.fetchFriendUpdates(account, authtoken,
- mLastUpdated);
-
- mLastUpdated = new Date();
-
- Log.d(TAG, "Calling contactManager's sync contacts");
- ContactManager.syncContacts(mContext, account.name, users);
-
- statuses = NetworkUtilities.fetchFriendStatuses(account, authtoken);
- ContactManager.insertStatuses(mContext, account.name, statuses);
- } catch (final AuthenticatorException e) {
- syncResult.stats.numParseExceptions++;
- Log.e(TAG, "AuthenticatorException", e);
- } catch (final OperationCanceledException e) {
- Log.e(TAG, "OperationCanceledExcetpion", e);
- } catch (final IOException e) {
- Log.e(TAG, "IOException", e);
- syncResult.stats.numIoExceptions++;
- } catch (final AuthenticationException e) {
- mAccountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE,
- authtoken);
- syncResult.stats.numAuthExceptions++;
- Log.e(TAG, "AuthenticationException", e);
- } catch (final ParseException e) {
- syncResult.stats.numParseExceptions++;
- Log.e(TAG, "ParseException", e);
- } catch (final JSONException e) {
- syncResult.stats.numParseExceptions++;
- Log.e(TAG, "JSONException", e);
- }
- }
onPerformSync中的執(zhí)行流程中,使用NetworkUtilities中的fetchFriendUpdates和fetchFriendStatuses來訪問服務(wù)端的聯(lián)系人更新,并使用了例程中自己封裝的ContactManager來讀取、更新聯(lián)系人信息。
那Account和SyncAdapter及其Service和xml定義之間是如何關(guān)聯(lián)的呢? AndroidManifest.xml中定義了AccountAuthenticator,SyncAdapter及對應(yīng)的Service和xml定義的關(guān)聯(lián)。
- <application
- android:icon="@drawable/icon"
- android:label="@string/label">
- <!-- The authenticator service -->
- <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>
- <activity
- android:name=".authenticator.AuthenticatorActivity"
- android:label="@string/ui_activity_title"
- android:theme="@android:style/Theme.Dialog"
- android:excludeFromRecents="true"
- >
- <!--
- No intent-filter here! This activity is only ever launched by
- someone who explicitly knows the class name
- -->
- </activity>
- </application>
更詳細(xì)的代碼細(xì)節(jié)和執(zhí)行流程,可以去把SDK中的SampleSyncAdapter代碼運(yùn)行起來體會一下,不過要實(shí)現(xiàn)整個流程,必須搭建聯(lián)系人的服務(wù)器端,例程中在目錄samplesyncadapter_server中也提供了簡單的server端python代碼,需要搭建在google app engine上。搭建過程遇到一些問題,由于對python不熟我弄了幾天才解決好搭建成功,其中遇到的一個model moudle找不到的問題需要你在model中新建一個__init__.py的空文件,來說明是一個python模塊,如果你也遇到此問題,希望對你有幫助。