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

Android 透過 Intent 讀取與更新通訊錄的實作教學

編輯:關於 Android 程式設計

一、簡介
本節示範如何在 Android 中透過使用者設定檔(user profile)讀取與更新手機上的所有聯絡人資訊,以及如何導航到設定檔中的這些聯絡人。

二、基本概念

1、什麼是 User Profile

使用者設定檔保存的是機主資訊以及該手機中所有聯絡人的資訊。假設手機所有者的名字是「Mao mao yu」,那麼 user profile 保存的就是「Mao mao yu」的通訊錄(即機主所有聯絡人的姓名、電話、郵箱等)。在 Android 4 中,這個保存聯絡人的應用稱為「People app」,而在 Android 5.0 及更高版本中則改稱「Contacts app」。

Android 6.0(API 23)模擬器已內建【通訊錄】功能,可直接手動添加機主姓名及聯絡人,如下圖:

點擊【通訊錄】中的某個聯絡人(例如機主的名字或其他聯絡人),就能在顯示的界面中修改姓名、電話、郵箱、住址等,或添加新聯絡人,這功能大家在手机上都很熟了,這裡不多說。本節的目標,是學習如何在自己的應用中透過程式碼去添加或修改這個 user profile,而不是用它本身的功能來編輯。

2、權限要求

要在程式中讀寫手機所有聯絡人的資料,應用必須具備 Read_Contacts 與 Write_Contacts 權限。此外,要讀取與編輯 user profile,還必須具備 Read_Profile 與 Write_Profile 權限。

也就是說,必須具備以下權限才能讀寫通訊錄與機主的 user profile:

READ_CONTACTS

READ_PROFILE

WRITE_CONTACTS

WRITE_PROFILE

實際上,手機上各類應用只要有對應權限,都能取得並修改你的通訊錄。一般使用者多半不是電腦背景,不太在意權限,一路按下一步,等於預設把完整的讀寫權限都交了出去。也就是說,只要你賦予這些應用讀寫權限,你的通訊錄實際上就毫無隱私可言,它們想什麼時候取就什麼時候取——這也正是許多免費手機應用拼命要你下載使用的原因之一。

下圖是在 VS2015 中設定 Read_Contacts 與 Read_Profile 的方式(點擊主選單【項目】下的【屬性】即可彈出):

用同樣方式可繼續設定 WRITE_CONTACTS 與 WRITE_PROFILE。

3、取得通訊錄資訊(Reading Profile Data)

Android 早期是透過 ContactsContracts.Contacts 類取得手機所有聯絡人列表。從 Android 4 起,又提供了 ContactsContact.Profile 類,它提供了對設備所有者 user profile 的訪問,利用它即可取得並修改所有聯絡人的名稱、電話號碼等。向 ContactsContact.Profile.ContentUri 發出查詢即可讀取設定檔資料,例如下面的程式碼讀取該 user profile 的顯示名稱:

 var uri = ContactsContract.Contacts.ContentUri; string[] projection = { ContactsContract.Contacts.InterfaceConsts.DisplayName }; var cursor = ContentResolver.Query(uri, projection, null, null, null); if (cursor.MoveToFirst ()) { Console.WriteLine(cursor.GetString (cursor.GetColumnIndex (projection [0]))); } 

4、更新聯絡人資訊(Update the User's Profile)

應用只要有對應讀寫權限,就能像其他普通應用一樣與 user profile 中的資料互動。例如呼叫 ContentResolver.Update 可更新設定檔中的顯示名稱,該方法透過 ContactsContract.Profile.ContentRawContactsUri 屬性檢索 Uri,如下:

 var values = new ContentValues (); values.Put (ContactsContract.Contacts.InterfaceConsts.DisplayName, "Mao mao yu"); ContentResolver.Update (ContactsContract.Profile.ContentRawContactsUri,values, null, null); 

注意:不能顯式創建 user profile,否則會出現異常。

接下來可建立一個 ReadBackName 方法,用來驗證加入 user profile 的名稱是否確實被更新。此方法先取得 user profile 的 URI 並設定投影,只讀取一列(使用者顯示名稱),再建立游標;若游標成功初始化,就移到第一項,讀取該列名稱並打印到控制台。成功則回傳 true,否則回傳 false。

 bool ReadBackName() { Android.Net.Uri uri = ContactsContract.Profile.ContentUri; string[] projection = { ContactsContract.Contacts.InterfaceConsts.DisplayName }; var cursor = ContentResolver.Query(uri, projection, null, null, null); if (cursor != null) { if (cursor.MoveToFirst()) { Console.WriteLine(cursor.GetString(cursor.GetColumnIndex(projection[0]))); return true; } } return false; } 

再加一個 ViewProfile 方法,它會自動呼叫 Contacts App 顯示 user profile 的資訊:

 void ViewProfile () { Intent intent = new Intent (Intent.ActionView, ContactsContract.Profile.ContentUri); StartActivity (intent); } 

注意:只有在 Android 4 及更高版本才能使用機主的 user profile。此外,在 user profile 可更新之前,必須先手動創建聯絡人。關於 ContactsContract.Profile 的更多資訊,請參見 ContactsContract.Profile 類。

三、示例—ch1204ReadContacts
本示例示範如何取得通訊錄中的聯絡人。

1、運行截圖

點擊【讀取通訊錄】按鈕,即得到右側截圖。

點擊【修改機主資訊】按鈕,即得到下面的修改界面:

下圖是在 Android 4.4.2(API 19) 下運行的結果:

2、主要設計步驟

(1)設定權限。在 VS2015 中選擇主選單的【項目】→【ContactsDemo 屬性】,在彈出視窗中勾選以下權限:

READ_CONTACTS

READ_PROFILE

WRITE_CONTACTS

WRITE_PROFILE

或在【方案總管】中雙擊項目的【Properties】進入設定,再勾選上述選項。設定完成後,AndroidManifest.xml 會自動添加:

 <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_PROFILE" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_PROFILE" /> 

(2)添加 ch1204_Main.axml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@android:color/background_light" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:text="讀取通訊錄" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnRead" /> <Button android:text="修改機主信息" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnUpdate" /> </LinearLayout> 

(3)添加 ch1204_ContactListItem.axml,放在 Resources/layout/ 下:

 <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="15dip" /> 

(4)添加 ch1204ReadContactActivity.cs:

 using System.Collections.Generic; using Android.App; using Android.Content; using Android.OS; using Android.Widget; using Android.Provider; namespace MyDemos.SrcDemos { [Activity(Label = "【例12-4】讀取和更新通訊錄")] public class ch1204ReadContactActivity : ListActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var uri = ContactsContract.Contacts.ContentUri; string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName }; var cursor = ContentResolver.Query(uri, projection, null, null, null); var contactList = new List<string>(); if (cursor.MoveToFirst()) { do { contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[1]))); } while (cursor.MoveToNext()); } cuesor.Close(); ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.ch1204_ContactListItem, contactList); } } } 

注意該類繼承自 ListActivity,而非 Activity。

(5)添加 ch1204ReadContactsMain.cs:

 using Android.App; using Android.Content; using Android.OS; using Android.Widget; using Android.Provider; namespace MyDemos.SrcDemos { [Activity(Label = "【例12-4】讀取和更新通訊錄")] public class ch1204ReadContactsMain : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ch1204_Main); var btnRead = FindViewById<Button>(Resource.Id.btnRead); btnRead.Click += delegate { StartActivity(typeof(ch1204ReadContactActivity)); }; var btnUpdate = FindViewById<Button>(Resource.Id.btnUpdate); btnUpdate.Click += delegate { NameOwner(); if (ReadBackName()) { Intent intent = new Intent(Intent.ActionView, ContactsContract.Profile.ContentUri); StartActivity(intent); } }; } /// <summary> /// 定義手機機主的名字 /// </summary> void NameOwner() { ContentValues values = new ContentValues(); //將“Rainmj”插入到已存在的user profile中 values.Put(ContactsContract.Contacts.InterfaceConsts.DisplayName, "Rainmj"); //更新user profile ContentResolver.Update(ContactsContract.Profile.ContentRawContactsUri, values, null, null); } /// <summary> /// 檢查“更新user profile”是否成功 /// </summary> /// <returns></returns> bool ReadBackName() { //獲取user profile的Uri Android.Net.Uri uri = ContactsContract.Profile.ContentUri; //配置投影,指定准備從user profile中讀取的列 string[] projection = { ContactsContract.Contacts.InterfaceConsts.DisplayName }; var cursor = ContentResolver.Query(uri, projection, null, null, null); if (cursor != null) { if (cursor.MoveToFirst()) { cursor.Close(); //Console.WriteLine(cursor.GetString(cursor.GetColumnIndex(projection[0]))); return true; } } return false; } } } 

以上就是本文的全部內容,希望對大家的學習有所幫助。

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