Android之内容提供器ContentProvider的简单表示

本文介绍如何使用ViewProvider和Java代码获取Android手机上的联系人信息。需在AndroidManifest.xml中添加READ_CONTACTS权限,并通过ContentResolver查询CommonDataKinds.Phone.CONTENT_URI来获取联系人姓名和电话号码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何通过ViewProvider得到手机联系人信息
首先,需要在Manifests里面添加权限:

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
```xml
**java代码:**




<div class="se-preview-section-delimiter"></div>

```java
public class TestContentProvider extends Activity {
    private Button mButton;
    private TextView mTextPhoneValues;
    private ContentResolver mResolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_content_provider);

        mTextPhoneValues = (TextView) findViewById(R.id.text_phone_values);
        mButton = (Button) findViewById(R.id.button_content_provider);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mResolver = getContentResolver();
                Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursor = mResolver.query(uri,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},null,null,null);
                cursor.moveToFirst();
                while(!cursor.isAfterLast()){
                    String[] names = cursor.getColumnNames();
                    StringBuffer buffer = new StringBuffer();
                    for(String name:names){
                        String value = cursor.getString(cursor.getColumnIndex(name));
                        buffer.append("字段名:"+name+"\t字段值:"+value);
                    }
                    mTextPhoneValues.setText(mTextPhoneValues.getText()+buffer.toString()+"\n");
                    cursor.moveToNext();
                 }
            }
        });
    }
}

布局文件很简单,只需添加一个按钮,和一个用来呈现信息的TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <Button
        android:id="@+id/button_content_provider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Provide Phone Number"/>
    <TextView
        android:id="@+id/text_phone_values"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

结果演示:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值