編輯:初階開發
本文節選自機械工業出版社《Android 應用開發揭秘》,作者楊豐盛。該書涵蓋 Android 框架、組件、使用者介面、遊戲開發、資料儲存、多媒體與網路開發等基礎,並深入探討感測器、語音辨識、桌面組件、遊戲引擎設計、效能優化與 OpenGL 等高階主題,同時介紹以 NDK(C/C++)及 Python、Lua 等腳本語言開發 Android 應用的方式。

Android 是一個面向應用的豐富平台,擁有眾多吸引人的介面元素與資料、網路管理能力。本章介紹幾項特別的接口:感測器系統(Sensor)、語音辨識(RecognizerIntent)、Google Map,以及桌面插件(Widget)開發。
Android 2.0 新增了 android.accounts 套件,提供集中式的帳戶管理 API,用以安全地儲存與存取認證權杖和密碼。情境很好理解:手機裡可能同時存在多個帳戶,各自承載不同資料,甚至各自與不同伺服器同步——例如聯絡人可以是某個 Gmail 帳戶的通訊錄,联网後自動更新。
表 9-3 android.accounts 套件功能描述

光看說明容易抽象,以下結合範例程式來看。範例實現了帳戶新增功能,可加入多個帳戶集中管理。點擊「新建帳戶」後即可填寫帳戶資訊。

圖 9-27 帳戶列表

圖 9-28 新建帳戶介面

圖 9-29 新建聯絡人
範例中共建立 4 個帳戶,因此退出程式後點擊新建聯絡人時,系統會要求選擇要在哪個帳戶下建立,實現了「獨立隔開、統一管理」的效果。完整程式碼請見原書第 9 章\Examples_09_08。
由於涉及帳戶資訊操作,必須先在 AndroidManifest.xml 中宣告權限,並確認 API 等級為 5:
<uses-sdk android:minSdkVersion="5"/> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/> <uses-permission android:name="android.permission.ACCOUNT_MANAGER"></uses-permission> <uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission> <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
UI 佈局部分可參考書中第 4 章。以圖 9-27 的 Activity 為例,需先透過 get 方法取得物件:
// 取得 AccountManager 物件 AccountManager _am = AccountManager.get(this);
AccountManager 提供了大量管理方法,用它可以輕鬆操作帳戶資料。例如列出指定類型的所有帳戶:
/* 顯示出所有帳戶 */
private void listAccounts() {
/* 得到指定類型的帳戶 */
Account[] accounts = _am.getAccountsByType(getString(R.string.ACCOUNT_TYPE));
_accountList.setText("帳戶列表:");
for (Account account : accounts) {
_accountList.setText(_accountList.getText().toString() + '\n' +
account.name + " - " + account.type);
}
}
重點在於把帳戶資訊寫入管理器。首先實作一個 AccountAuthenticatorActivity 供使用者輸入資料,如代碼清單 9-15。
代碼清單 9-15 SleepyAccountAuthenticatorActivity.java
public class SleepyAccountAuthenticatorActivity extends AccountAuthenticatorActivity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.new_account);
final Button done = (Button) findViewById(R.id.new_account_done);
final EditText server = (EditText) findViewById(R.id.new_account_server);
final EditText username = (EditText) findViewById(R.id.new_account_username);
final EditText passWord = (EditText) findViewById(R.id.new_account_passWord);
final Activity self = this;
done.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Account:指定帳戶名與帳戶類型
Account account = new Account(username.getText().toString(),
getString(R.string.ACCOUNT_TYPE));
// 伺服器資料
Bundle userdata = new Bundle();
userdata.putString("SERVER", server.getText().toString());
// 取得 AccountManager
AccountManager am = AccountManager.get(self);
// 新增一個帳戶
if (am.addAccountExplicitly(account, passWord.getText().toString(), userdata)) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME,
username.getText().toString());
result.putString(AccountManager.KEY_ACCOUNT_TYPE,
getString(R.string.ACCOUNT_TYPE));
setAccountAuthenticatorResult(result);
}
finish();
}
});
}
}
流程很清楚:先用帳戶名與類型建構 Account 物件,把伺服器資訊以 Bundle 帶入,最後呼叫 addAccountExplicitly 寫入管理器。
接著需要一個 Service 與一個 AbstractAccountAuthenticator。先建立 authenticator.xml(代碼清單 9-16):
代碼清單 9-16 res/xml/authenticator.xml
<?xml version="1.0" encoding="utf-8"?>
<account-authenticator xmlns:android="https://schemas.android.com/apk/res/android"
android:accountType="com.yarin.AccountType"
android:icon="@drawable/icon"
android:smallIcon="@drawable/icon"
android:label="@string/ACCOUNT_LABEL"
android:accountPreferences="@xml/account_preferences"
/>
然後在 AndroidManifest.xml 中啟動帳戶管理服務:
<service android:name="SleepyAccountsService">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/authenticator" />
</service>
服務類的實作很單純:當 action 為 ACTION_AUTHENTICATOR_INTENT 時,透過 getIBinder 回傳 Binder(代碼清單 9-17)。
代碼清單 9-17 SleepyAccountsService.java
public class SleepyAccountsService extends Service {
private SleepyAccountAuthenticator _saa;
public IBinder onBind(Intent intent) {
IBinder ret = null;
if (intent.getAction().equals(
android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) {
ret = getSleepyAuthenticator().getIBinder();
}
return ret;
}
private SleepyAccountAuthenticator getSleepyAuthenticator() {
if (_saa == null) {
_saa = new SleepyAccountAuthenticator(this);
}
return _saa;
}
}
最重要的一塊是 AbstractAccountAuthenticator,因為新增與操作帳戶時的異步呼叫都會經由它。以下是 addAccount 的實作(代碼清單 9-18):
代碼清單 9-18 addAccount 方法
/* 新增帳戶 */
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
String authTokenType, String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Log.d(_tag, accountType + " - " + authTokenType);
Bundle ret = new Bundle();
Intent intent = new Intent(_context, SleepyAccountAuthenticatorActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
ret.putParcelable(AccountManager.KEY_INTENT, intent);
return ret;
}
帳戶管理概念相對抽象,建議務必搭配範例程式一起讀,並參考 Android 2.0 SDK 文件中的 AccountManager 與 AbstractAccountAuthenticator 說明。
本章各節之間關聯性不強,都是 Android 的特色功能切片:感測器、語音辨識、Google Map API、桌面組件,以及帳戶管理。這些能力在日常應用中相當常見,從 GPS 導航到路徑規劃都有發揮空間,值得細讀並轉化為自己的創意題材。
Android 自訂通知列:RemoteViews 與 ProgressBar 的組合應用
系統預設的通知樣式只能放標題、內文與小圖示。若你的情境需要更豐富的呈現——例如顯示下載進度——就得自己指定通知的版面。 以下是我實作的通知效果,核心程式碼如下: nf
Android 軟鍵盤彈出時的版面縮放行為與監聽技巧
Android 是為觸控螢幕設計的系統,點擊輸入框時會自動彈出軟鍵盤。但鍵盤一出現,可用高度就變少了——系統該如何處理這段被壓縮的空間?我們能不能自行控制?這是本文想釐清
Android GridView 網格版面實作:自定義 ImageAdapter
先前提到過 GridView 也是一種 AdapterView,和 ListView 頗為相似。實際用過一輪之後有些心得,在此分享。 思路 1. 既然與 ListVie
Android Logcat 無法顯示中文的解決辦法
用 Eclipse 調試 Android 程序時,很多人會遇到 Logcat 裡中文變成問號或亂碼的情況。平時也許無所謂,但一旦需要觀察網絡數據的解析結果,中文可視與否就