Android應用開發筆記(2):讀取手機中的連絡人資訊(android.provider.ContactsContract)

來源:互聯網
上載者:User

本文來自http://blog.csdn.net/xjanker2 ,引用轉載必須註明出處!

上一篇中使用了打電話發簡訊的功能,但號碼連絡人資訊我們還不知道。本篇開始講如何從Android中得到本機連絡人的資訊。

由於Android較快的版本升級,部分API已經發生了變化。本篇探究的通過ContentProvider機制擷取連絡人的API從Android2.0開始做了很大調整,原來的android.provider.Contacts類及其下相關類由android.provider.ContactsContract代替。原類體系標記為Deprecated(廢棄),因為相容的原因目前還存在,但不保證以後的更新版本中完全丟棄。

 

所以本文先從Android2.1以上平台的連絡人讀取開始說起,下面給出代碼在Android2.1/2.2中啟動並執行,

 

 

首先,建立類ViewContacts繼承ListActivity,並設為為應用的開始Activity。

ViewContacts.java 代碼:

 package jtapp.contacts;</p><p>import java.util.ArrayList;<br />import java.util.HashMap;<br />import java.util.List;</p><p>import android.app.ListActivity;<br />import android.database.Cursor;<br />import android.os.Bundle;<br />import android.provider.ContactsContract;<br />import android.widget.SimpleAdapter;</p><p>public class ViewContacts extends ListActivity {<br /> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);</p><p> List<HashMap<String, String>> items = fillMaps();<br /> SimpleAdapter adapter = new SimpleAdapter(<br /> this,items,R.layout.list_item,<br /> new String[]{"name","key"},<br /> new int[]{R.id.item,R.id.item2});<br /> this.setListAdapter(adapter);</p><p> }</p><p>private List<HashMap<String, String>> fillMaps() {<br />List<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();</p><p>Cursor cur = null;<br />try {<br />// Query using ContentResolver.query or Activity.managedQuery<br />cur = getContentResolver().query(<br />ContactsContract.Contacts.CONTENT_URI, null, null, null, null);<br />if (cur.moveToFirst()) {<br />int idColumn = cur.getColumnIndex(<br />ContactsContract.Contacts._ID);<br /> int displayNameColumn = cur.getColumnIndex(<br /> ContactsContract.Contacts.DISPLAY_NAME);<br />// Iterate all users<br /> do {<br />String contactId;<br />String displayName;<br />String phoneNumber = "";<br />// Get the field values<br />contactId = cur.getString(idColumn);<br />displayName = cur.getString(displayNameColumn);<br />// Get number of user's phoneNumbers<br />int numberCount = cur.getInt(cur.getColumnIndex(<br />ContactsContract.Contacts.HAS_PHONE_NUMBER));<br />if (numberCount>0) {<br />Cursor phones = getContentResolver().query(<br />ContactsContract.CommonDataKinds.Phone.CONTENT_URI,<br />null,<br />ContactsContract.CommonDataKinds.Phone.CONTACT_ID<br />+ " = " + contactId<br />/*+ " and " + ContactsContract.CommonDataKinds.Phone.TYPE<br />+ "=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE*/,<br />null, null);<br />if (phones.moveToFirst()) {<br />int numberColumn = phones.getColumnIndex(<br />ContactsContract.CommonDataKinds.Phone.NUMBER);<br />// Iterate all numbers<br />do {<br />phoneNumber += phones.getString(numberColumn) + ",";<br />} while (phones.moveToNext());<br />}<br />}<br />// Add values to items<br />HashMap<String, String> i = new HashMap<String, String>();<br />i.put("name", displayName);<br />i.put("key", phoneNumber);<br />items.add(i);<br />} while (cur.moveToNext());<br />} else {<br />HashMap<String, String> i = new HashMap<String, String>();<br />i.put("name", "Your Phone");<br />i.put("key", "Have No Contacts.");<br />items.add(i);<br />}<br />} finally {<br />if (cur != null)<br />cur.close();<br />}<br />return items;<br />}<br />}

 

 main.xml 代碼:

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="show your phone's contacts:"<br /> /><br /><ListView android:id="@id/android:list"<br /> android:layout_width="fill_parent"<br /> android:layout_height="0dip"<br /> android:layout_weight="1"<br /> android:drawSelectorOnTop="false"<br /> /><br /></LinearLayout>

list_item.xml 代碼:

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><TableRow android:id="@+id/TableRow01"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"><br /><TextView android:id="@+id/item"<br /> xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:textSize="20px" /><br /><TextView android:text=": "<br /> xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:textSize="20px" /><br /><TextView android:id="@+id/item2"<br /> xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:textSize="20px" /><br /></TableRow><br /></LinearLayout>

 

AndroidManifest.xml 增加uses許可權READ_CONTACTS 代碼:

<?xml version="1.0" encoding="utf-8"?><br /><manifest xmlns:android="http://schemas.android.com/apk/res/android"<br />package="jtapp.contacts" android:versionCode="1" android:versionName="1.0"><br /><application android:icon="@drawable/icon" android:label="@string/app_name"><br /><activity android:name=".ViewContacts" android:label="@string/app_name"><br /><intent-filter><br /><action android:name="android.intent.action.MAIN" /><br /><category android:name="android.intent.category.LAUNCHER" /><br /></intent-filter><br /></activity><br /></application><br /><uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission><br /></manifest>

 

以上檔案編寫好後,應用就能夠在Android2.1模擬器上正確運行了。

 

那麼該app如果在android1.6上運行,會怎麼樣呢?1.6上並沒有ContactsContract類體系,所以就會報錯了。需要注意,ContactContract類是在API Level 5增加的,之前的Android版本並不支援。

在Android 1.6 (API Level 4)上,擷取連絡人的方法將fillMaps()實現為如下:

 private List<HashMap<String, String>> fillMaps() {<br />List<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();</p><p>Cursor cur = null;<br />try {<br />// Form an array specifying which columns to return.<br />String[] projection = new String[] {<br />People._ID,<br />People.NAME,<br />People.NUMBER<br />};<br />// query using ContentResolver.query or Activity.managedQuery<br />cur = getContentResolver().query(<br />People.CONTENT_URI,projection, null,null, null);<br />if (cur.moveToFirst()) {<br />String name;<br />String phoneNumber;<br />int nameColumn = cur.getColumnIndex(People.NAME);<br />int phoneColumn = cur.getColumnIndex(People.NUMBER);<br />do {<br />// Get the field values<br />name = cur.getString(nameColumn);<br />phoneNumber = cur.getString(phoneColumn);<br />// Do something with the values.<br />HashMap<String, String> i = new HashMap<String, String>();<br />i.put("name", name);<br />i.put("key", phoneNumber);<br />items.add(i);<br />} while (cur.moveToNext());<br />} else {<br />HashMap<String, String> i = new HashMap<String, String>();<br />i.put("name", "Your Phone");<br />i.put("key", "Have No Contacts.");<br />items.add(i);<br />}<br />} finally {<br />if (cur != null)<br />cur.close();<br />}<br />return items;<br />}

 

 那麼就能在1.6上運行了,效果如下:

連絡人API,在Android2.0後產生變化,如果使用如上1.6版本的調用,你會發現在2.1下姓名有了,但電話號碼不顯示了。仔細觀察可以發現,People.CONTENT_URI等調用在2.0以上的sdk中都標記了Deprecated。這一點,對於編寫希望能夠同時相容1.6與2.x版本的應用造成了困難。那麼,如果應用涉及到連絡人的讀取,非得要編寫多個版本的apk了嗎? 其實,我們可以使用判斷當前系統API Level的方法編寫兩套代碼備用,這個就留給大家去實踐了。

 

獲得系統API level方法:

int version = android.provider.Settings.System.getInt(context<br /> .getContentResolver(),<br /> android.provider.Settings.System.SYS_PROP_SETTING_VERSION,<br /> 3);</p><p>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.