Android uses intent to read and update address Books _android

Source: Internet
Author: User

First, Introduction
This section shows how to read and update all contact information for the phone through the user profile in an Android system, and how to navigate to those contacts in the user profile.

Ii. Basic Concepts
1. What is User profile

The user profile saves information about the machine master and all contacts on the phone.

Assuming the name of the handset owner is "Mao Mao Yu," The user profile keeps the address Book of "Mao Mao Yu" (the name, phone number, mailbox 、...... of all the owners ' contacts). and other information). In Android 4, the application that holds the contact information is called the "People App", and in Android 5.0 and later, the app is renamed "Contacts app".

The Android 6.0 (API 23) emulator already contains the "Address Book" feature, which allows you to manually add the name of the phone owner and its contact person, as shown in the following illustration:

Click a contact in the address book, such as clicking on the name of the owner (or the name of another contact), can be in the display of the interface to modify the person's name, phone, mailbox, address and other information, or add a new contact person, this feature is used on mobile phones too familiar, here is not more to say.

Our goal in this section is to learn how to add or modify information in the user profile in your own application, rather than using the functionality it provides.

2. Permission Requirements

To read and write data about all your phone's contacts in your program, your application must have Read_contacts and Write_contacts permissions. In addition, to read and edit the user profile, your application must have Read_profile and Write_profile permissions.

Alternatively, you must have the following permissions to read and write the Address Book and the user profile of the machine master:

Read_contacts

Read_profile

Write_contacts

Write_profile

In fact, the types of apps you download on your phone, as long as the corresponding permissions, you can get and modify your address book (the general mobile phone users are not engaged in computer, and therefore do not care about what permissions, directly next to the point down, the result is the default to these programs give the full read and write permissions). Or, as long as you give these applications the appropriate read and write access, so your address book is actually not a bit of security, and when it's time to get it (it's too easy to get out of the way), that's why so many free mobile apps are desperately trying to get you to download and use them.

The following figure is a way to set up read_contacts and Read_profile in VS2015 (this interface is ejected by clicking Properties under the main Menu "items"):

In the same way, you can continue to set write_contacts and Write_profile permissions.

3, get Address Book information (Reading profile data)

The early version of Android was to get a list of all the contacts on the phone through the Contactcontracts.contacts class. Starting with Android 4, a new Contactscontact.profile class provides access to the device owner user profile, which allows you to get and modify all contact names, phone numbers, and so on.

You can read the configuration file's data by issuing a query to ContactsContact.Profile.ContentUri. For example, the following code reads the display name of the 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 contact information (update the User ' s profile)

An application can interact with the data in the user profile, like other ordinary applications, as long as it has the appropriate read and write permissions. For example Call the Contentresolver.update method to update the display name in the configuration file, which retrieves the URI through the ContactsContract.Profile.ContentRawContactsUri property, as shown in the following code:

var values = new Contentvalues (); 

Values. Put (ContactsContract.Contacts.InterfaceConsts.DisplayName, "Mao Mao Yu"); 

Contentresolver.update (contactscontract.profile.contentrawcontactsuri,values, NULL, NULL); 

Note: You cannot explicitly create a user profile (users ' s profiile), otherwise an exception will occur.

Next, you can create a Readbackname method, as shown in the following code. Call this method to verify that the name added to the user profile has indeed been updated. In this method, you first get the URI of the user's configuration file and configure the projection to read only one column from this configuration file (the user's display name). To access the user's profile data, a cursor object is created next. If the cursor is successfully initialized, it is moved to the first item in the user's profile. Read the name in the first column of this location (the user displays the name) and print it to the console. Readbackname returns True if these operations succeed, otherwise it returns 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; 

} 

Add a Viewprofile method that automatically calls the Contacts app to display the information in the user profile:

void Viewprofile () 

{ 

 Intent Intent = new Intent (Intent.actionview, ContactsContract.Profile.ContentUri); C19/>startactivity (intent); 

} 

Note: the user profile of the handset owner can only be used in Android 4 and later. In addition, you must manually create a contact before the user profile can be updated.

For more information about Contactcontracts.profile, see the Contactscontract.profile class.

Third, sample-ch1204readcontacts
This sample shows how to get contacts in the Address Book.

1, run the screenshot

Click the "read Address Book" button to get a screenshot of the right below.

Click the Modify Machine Master button to get the following modification interface:

The following figure is the result of running under the Android 4.4.2 (API 19):

2. Main design Steps

(1) Set permissions

In the VS2015 development environment, select the "Items" à "contactsdemo properties" of the main menu, and check the pop-up window for the following permissions:

Read_contacts

Read_profile

Write_contacts

Write_profile

Or, in Solution Explorer, double-click the project's Properties to enter the settings interface, and then check the options above.

When you are finished, the following code is automatically added to the Androidmanifest.xml file:

<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) Add Ch1204_main.axml file

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://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 = "Read Address Book"
 android:layout_width= "match_parent" android:layout_height= "wrap_content"
 android:id= "@+ Id/btnread "/>
 <button
 android:text=" Modify machine Master information
 android:layout_width= "Match_parent
 " android:layout_height= "Wrap_content"
 android:id= "@+id/btnupdate"/>
</LinearLayout>

(3) Add Ch1204_contactlistitem.axml file

Add the file under resources/layout/.

<?xml version= "1.0" encoding= "Utf-8"?> <textview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:layout_width=" fill_parent "
 android:layout_height=" fill_parent "
 android:padding=" 15dip "/> 

(4) Add Ch1204ReadContactActivity.cs file

 using System.Collections.Generic; using Android.app; using Android.content; using and Roid.
OS;
Using Android.widget;

Using Android.provider; 
 namespace Mydemos.srcdemos {[Activity (Label = ' example 12-4 ' read and update Address Book ')] 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); }
 }
}

Note that this class inherits from Listactivity and does not inherit from the activity.

(5) Add Ch1204ReadContactsMain.cs file

Using Android.app;
Using Android.content;
Using Android.os;
Using Android.widget;

Using Android.provider; namespace Mydemos.srcdemos {[Activity (Label = ' example 12-4 ' read and update Address Book ')] public class Ch1204readcontactsmain:activity {PR otected 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>///defines the name of the mobile phone master///</summary> void Nameowner () {contentvalues values = new Contentvalue
 S (); Insert "RAINMJ" into the existing user profile values. Put (CONTACTSCONTRACT.CONTACTS.INTERFACECONSTS.DISPLAyname, "RAINMJ");
 Update user profile contentresolver.update (ContactsContract.Profile.ContentRawContactsUri, values, NULL, NULL); ///<summary>///Check "Update user profile" Success///</summary>///<returns></returns> bool Readb

 Ackname () {//Gets the URI Android.Net.Uri uri = ContactsContract.Profile.ContentUri for user profile;

 Configure the projection to specify the column string[] projection = {ContactsContract.Contacts.InterfaceConsts.DisplayName} to be read from the user profile;
 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;

 }
 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.