使用内容提供者——Contacts

作者:追风剑情 发布于:2015-8-18 22:19 分类:Android

使用内容提供者contacts获取手机中所有联系人,并显示在列表中。

一、在AndroidManifest.xml中添加权限

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

二、创建活动

视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <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:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/contactID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

代码

package com.example.androidtest;

import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.SimpleCursorAdapter;
import android.widget.CursorAdapter;

public class ProviderActivity extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_provider);
		
		Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
		//等价于:
		//Uri allContacts = Uri.parse("content://contacts/people");
		
		Cursor c;
		if (android.os.Build.VERSION.SDK_INT < 11) {
			c = managedQuery(allContacts, null, null, null, null);
			//等价于:
			//c = getContentResolver().query(allContacts, null, null, null, null);
			//startManagingCursor(c);
		} else {
			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.activity_provider, c, columns, views);
		} else {
			adapter = new SimpleCursorAdapter(
					this, R.layout.activity_provider, c, columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		}
		
		//必须使用默认id: "@+id/android:list" 才能使用setListAdapter();
		this.setListAdapter(adapter);
	}
}

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号