如何通过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>
结果演示: