編輯:Android 開發教學
理解 ContentProvider 最好的方式就是親手做一遍。以下示範如何使用內建的 Contacts Provider。
新建一個名為 Provider 的專案。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="false"
android:transcriptMode="normal" />
<TextView
android:id="@+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="@+id/contactID"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
public class ProviderActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
Cursor c;
if (android.os.Build.VERSION.SDK_INT < 11) {
// Honeycomb 之前
c = managedQuery(allContacts, null, null, null, null);
} else {
// Honeycomb 之後改用 CursorLoader
CursorLoader cursorLoader =
new CursorLoader(this, allContacts, null, null, null, null);
c = cursorLoader.loadInBackground();
}
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID
};
int[] views = new int[] {
R.id.contactName,
R.id.contactID
};
SimpleCursorAdapter adapter;
if (android.os.Build.VERSION.SDK_INT < 11) {
adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, views);
} else {
adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, views,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
this.setListAdapter(adapter);
}
}
第一,一定要在 AndroidManifest.xml 加上 <uses-permission android:name="android.permission.READ_CONTACTS" />,否則 query 會直接失敗(在 6.0 以上還必須向使用者動態請求)。
第二,managedQuery 在 Honeycomb 之後已被標記為不建議使用,因為它綁在 Activity 生命週期上,重啟時容易拿到過期資料;改用 CursorLoader 才能正確在背景執行並自動監聽資料變化。
第三,SimpleCursorAdapter 的 _ID 欄位是必需的——ListView 需要它作為每列的穩定識別,少了它就會出現位置錯亂或當機。
Android 開發教學:建立第一個 Hello World
建立 Android 專案後,即可開始第一個 Hello World 應用。步驟在 Eclipse 選擇 Android Project,設定專案名稱、Build Tar
Android 手機間無線互傳的技術選型與實作
先前研究了一下 Android 該怎麼做到無線互傳,寫了個小 demo,最近整理出來與大家分享。 技術選型 1. 藍牙:歷史悠久、簡單易用,但速度實在太慢,是致命傷。 2
ApiDemos 解析:自訂 Dialog 主題
自訂 Dialog 風格可讓 Activity 呈現特定視覺樣式。Theme 與 StyleTheme 可套用到 Activity 或 Application,Style
Android 中檢測 Wi-Fi 與行動網絡狀態
許多 Android 應用需要判斷目前是否連上網路。Android 提供 ConnectivityManager,可用來查詢 Wi-Fi 與行動數據的狀態。取得網路狀態透