Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ContentProvider 實戰:讀取系統聯絡人(含版本相容處理)

編輯:Android 開發教學

理解 ContentProvider 最好的方式就是親手做一遍。以下示範如何使用內建的 Contacts Provider。

一、建立專案

新建一個名為 Provider 的專案。

二、main.xml

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

三、ProviderActivity.java

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 需要它作為每列的穩定識別,少了它就會出現位置錯亂或當機。

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