編輯:Android 開發實例
用過 Android 版的 Facebook、last.fm 的人,應該都對它們能定期更新好友動態、把最新近況與心情整合進聯絡人的功能印象深刻。這些應用全都建立在 Android 2.0 之後的帳戶與同步機制之上。Google 的範例 SampleSyncAdapter 就是很好的學習素材,透過它能理解 Android 的帳戶驗證與同步 Adapter 用法。
以下以 2.2 版本的 SDK 範例為例說明(完整程式碼可見 SDK samples)。
類別 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 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 模組。
Android 手勢(Gesture)處理:從單擊、滑動到多點縮放
觸控螢幕上的操作千變萬化,Android 把幾種常見的動作抽象成「手勢」:點擊、長按、滑動、快速滑動(Fling)、雙指捏合縮放等。應用程式只要攔截這些手勢,就能提供更自
Android JSON 解析實戰:用天氣 API 學會 JSONObject
JSON(JavaScript Object Notation)長期以來都是應用程式交換資料的首選格式。相較於 XML,它更輕量、可讀性更高,也不需要額外的解析器,因此幾
Android 二級下拉菜單與實時搜索聯動的實現方法
需求很常見:頁面上方一個搜索框,下方一個兩級菜單;有輸入時展示搜索結果列表,清空輸入後恢復菜單。本文用 ExpandableListView + ListView 的顯示
Android ApiDemo 系列十:QuickContactsDemo 與 Content Provider
在 Android 的 ApiDemo 中,QuickContactsDemo 常用來示範如何透過 Content Provider 存取系統聯絡人資料。Content