[Android] 12.5 uses Intent to read and update Address Book, androidintent

Source: Internet
Author: User

[Android] 12.5 uses Intent to read and update Address Book, androidintent

Category: C #, Android, VS2015;

Created on: 1. Introduction

This section describes how to read and update all contacts on the mobile phone through the user profile in Android and how to navigate to these contacts in the user configuration file. Ii. Basic Concepts

1. What is User Profile?

The user profile stores the host information and information of all contacts on the mobile phone.

Assume that the mobile phone owner's name is "Mao mao yu". Then, the user profile stores the "Mao mao yu" Address Book (that is, the name, phone number, email address ,...... ). In Android 4, the application that saves contact information is called "People app". In Android 5.0 and later versions, this application is also called "Contacts app ".

The Android 6.0 (API 23) Simulator already contains the address book function, which allows you to manually add the name and contact of the mobile phone owner, as shown in:

Click a contact in address book, for example, the host name (or the name of another contact ), you can modify the name, phone number, email address, and other information of the person on the displayed interface, or add a new contact. This feature is very familiar with mobile phones, I will not talk about it here.

The goal of this section is to learn how to add or modify information in the user profile in your own application through code, instead of using its own functions to edit.

2. Permission requirements

To read and write data of all contacts on the mobile phone 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.

Or, you must have the following permissions to read and write the address book and the user configuration file of the Host:

READ_CONTACTS

READ_PROFILE

WRITE_CONTACTS

WRITE_PROFILE

In fact, all the applications downloaded on your mobile phone can obtain and modify your address book as long as they have the corresponding permissions (generally, mobile phone users do not engage in computers, therefore, I am not very concerned about what permissions are not permitted. Simply click Next. The result is that these programs are granted full read and write permissions by default ). Or, as long as you grant the corresponding read and write permissions to these applications, your address book is actually not secure, these apps can be obtained whenever they want (it is too easy to leak out), which is why there are so many free mobile apps that are desperately allowing you to download and use them.

Set Read_Contacts and Read_Profile in VS2015 (this interface is displayed by clicking properties under the main menu project ):

In the same way, you can continue to set WRITE_CONTACTS and WRITE_PROFILE permissions.

3. Get the address book information (Reading Profile Data)

In earlier versions of Android, The ContactContracts. Contacts class is used to obtain the list of all Contacts on the mobile phone. A new ContactsContact is provided from Android 4. profile class, which provides access to the user profile of the device owner, which can be used to obtain and modify the name and phone number of all contacts.

Send a query to ContactsContact. Profile. ContentUri to read the data in the configuration file. For example, the following code reads the display name of the user configuration file:

Var uri = ContactsContract. Contacts. ContentUri;

String [] projection = {

ContactsContract. Contacts. InterfaceConsts. DisplayName

};

Var cursor = ContentResolver. Query (uri, projection, null );

If (cursor. MoveToFirst ()){

Console. WriteLine (cursor. GetString (cursor. GetColumnIndex (projection [0]);

}

4. Update the User's Profile)

As long as the application has the corresponding read and write permissions, it can interact with the data in the user profile just like other common applications. For example, you can call ContentResolver. Update to Update the display name in the configuration file. This method retrieves the Uri through the ContactsContract. Profile. ContentRawContactsUri attribute, 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 (user's profiile); otherwise, an exception occurs.

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 configuration file is indeed updated. In this method, you first obtain the URI of the configuration file and configure the projection. Only one column (the display name of the user) is read from the configuration file ). To access the user's configuration file data, a cursor object is created. If the cursor is successfully initialized, it is moved to the first item in the user configuration file. Read the name in the first column of this location (User display name) and print it to the console. If these operations are successful, ReadBackName returns true; otherwise, false.

Bool ReadBackName ()

{

Android. Net. Uri uri = ContactsContract. Profile. ContentUri;

String [] projection = {ContactsContract. Contacts. InterfaceConsts. DisplayName };

Var cursor = ContentResolver. Query (uri, projection, null );

If (cursor! = Null)

{

If (cursor. MoveToFirst ())

{

Console. WriteLine (cursor. GetString (cursor. GetColumnIndex (projection [0]);

Return true;

}

}

Return false;

}

Add a ViewProfile method, which automatically calls the Contacts App to display the information in the user profile:

Void ViewProfile ()

{

Intent intent = new Intent (Intent. ActionView, ContactsContract. Profile. ContentUri );

StartActivity (intent );

}

Note: The user configuration file of the mobile phone owner can be used only in Android 4 and later versions. In addition, you must manually create a contact before the user configuration file can be updated.

For more information about ContactContracts. Profile, see the ContactsContract. Profile class. Iii. Example-ch1204ReadContacts

This example shows how to obtain contacts in the address book.

1. Run

Click Read address book.

Click Modify host information to obtain the following modification page:

2. Main design steps

(1) Set permissions

In the VS2015 development environment, select project & gt; ContactsDemo properties on the main menu and select the following permissions in the pop-up window:

READ_CONTACTS

READ_PROFILE

WRITE_CONTACTS

WRITE_PROFILE

Alternatively, in Solution Explorer, double-click Properties of the project to go to the settings page, and select the above options.

After setting, 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 and modify the 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 host information" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: id = "@ + id/btnUpdate"/> </LinearLayout>

(3) Add the 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 the ch1204ReadContactActivity. cs File

Using System. collections. generic; 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 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); var contactList = new List <string> (); if (cursor. moveToFirst () {do {contactList. add (cursor. getString (cursor. getColumnIndex (projection [1]);} while (cursor. moveToNext ();} ListAdapter = new ArrayAdapter <string> (this, Resource. layout. ch1204_ContactListItem, contactList );}}}

Note that this class is inherited from ListActivity rather than Activity.

(5) Add the 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 {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> // define the name of the mobile phone host /// </summary> void NameOwner () {Con TentValues values = new ContentValues (); // 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 whether "user profile is successfully updated" /// </summary> /// <returns> </returns> bool ReadBackName () {// obtain the Uri Android of the user profile. net. uri Uri = ContactsContract. profile. contentUri; // configure the projection. Specify the string [] projection = {ContactsContract. contacts. interfaceConsts. displayName}; var cursor = ContentResolver. query (uri, projection, null); // or // CursorLoader loader = new CursorLoader (this, uri, projection, null ); // var cursor = (ICursor) loader. loadInBackground (); if (cursor! = Null) {if (cursor. moveToFirst () {// Console. writeLine (cursor. getString (cursor. getColumnIndex (projection [0]); return true ;}} return false ;}}}

The running result is as follows.

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.