Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發筆記(7):打造自訂帳戶與內容同步機制——SampleSyncAdapter 解析

編輯:Android 開發實例

用過 Android 版的 Facebook、last.fm 的人,應該都對它們能定期更新好友動態、把最新近況與心情整合進聯絡人的功能印象深刻。這些應用全都建立在 Android 2.0 之後的帳戶與同步機制之上。Google 的範例 SampleSyncAdapter 就是很好的學習素材,透過它能理解 Android 的帳戶驗證與同步 Adapter 用法。

以下以 2.2 版本的 SDK 範例為例說明(完整程式碼可見 SDK samples)。

帳戶驗證:Authenticator

類別 Authenticator extends AbstractAccountAuthenticator 是帳戶認證類。開啟手機設定中的「帳戶與同步」時,其中的帳號功能就是由它實作。

// in Authenticator.java

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 定義新增帳號時的操作,此處會喚起 AuthenticatorActivity 進行帳號添加與認證。

在 AuthenticatorActivity.java 中,handleLogin() 透過 login_activity.xml 裡的 android:onClick="handleLogin" 與 UI 的 OK 按鈕關聯:

// in layout/login_activity.xml

<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 中的使用者名稱與密碼,建立一個驗證執行緒,透過網路向伺服器認證:

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);

    }

}

NetworkUtilities.authenticate() 負責實際的網路驗證流程,取得伺服器結果後,透過 sendResult() 以 handler.post 觸發 AuthenticatorActivity 中的 onAuthenticationResult():

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) {

            sendResult(true, handler, context);

            return true;

        } else {

            sendResult(false, handler, context);

            return false;

        }

    } catch (final IOException e) {

        sendResult(false, handler, context);

        return false;

    }

}

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);

        }

    });

}

onAuthenticationResult() 依驗證結果決定結束認證或再次嘗試:

public void onAuthenticationResult(boolean result) {

    hideProgress();

    if (result) {

        if (!mConfirmCredentials) { finishLogin(); }

        else { finishConfirmCredentials(true); }

    } else {

        if (mRequestNewAccount) {

            mMessage.setText(getText(R.string.login_activity_loginfail_text_both));

        } else {

            mMessage.setText(getText(R.string.login_activity_loginfail_text_pwonly));

        }

    }

}

內容同步:SyncAdapter

帳戶驗證完成、帳號建立後,就能使用同步功能。主要邏輯在 SyncAdapter extends AbstractThreadedSyncAdapter 中實作。

@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();

        ContactManager.syncContacts(mContext, account.name, users);

        statuses = NetworkUtilities.fetchFriendStatuses(account, authtoken);

        ContactManager.insertStatuses(mContext, account.name, statuses);

    } catch (final AuthenticatorException e) {

        syncResult.stats.numParseExceptions++;

    } catch (final OperationCanceledException e) {

    } catch (final IOException e) {

        syncResult.stats.numIoExceptions++;

    } catch (final AuthenticationException e) {

        mAccountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken);

        syncResult.stats.numAuthExceptions++;

    } catch (final ParseException e) {

        syncResult.stats.numParseExceptions++;

    } catch (final JSONException e) {

        syncResult.stats.numParseExceptions++;

    }

}

流程中使用 NetworkUtilities 的 fetchFriendUpdates 與 fetchFriendStatuses 向伺服器取得聯絡人更新,並用範例自封裝的 ContactManager 讀寫聯絡人資訊。

把元件串起來

Account、SyncAdapter 與其 Service、XML 定義的關聯,都在 AndroidManifest.xml 中宣告:

<application android:icon="@drawable/icon" android:label="@string/label">

<!-- 認證服務 -->

<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">

</activity>

</application>

更細節的程式流程,建議把 SDK 的 SampleSyncAdapter 跑起來實際體會。要跑完整流程,需先架好聯絡人的伺服器端;範例在 samplesyncadapter_server 目錄提供了簡單的 Python server 端程式碼,需部署在 Google App Engine 上。過程中若遇到找不到 model module 的問題,可在 model 目錄中新增一個空的 __init__.py 檔,以宣告這是一個 Python 模組。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved