Android ContentProvider实现获取手机联系人功能
程序员文章站
2022-05-17 22:35:54
在之前项目中有用到关于获取手机联系人的部分,闲置就想和大家分享一下,话不多说,上代码:
java部分:
package com.example.cont...
在之前项目中有用到关于获取手机联系人的部分,闲置就想和大家分享一下,话不多说,上代码:
java部分:
package com.example.content; import android.content.contentresolver; import android.database.cursor; import android.net.uri; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.util.log; import android.view.view; public class mainactivity extends appcompatactivity { private contentresolver cr; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //获取内容访问者 cr = getcontentresolver(); } public void getcontacts(view view){ uri uri=uri.parse("content://com.android.contacts/raw_contacts"); cursor cursor=cr.query(uri,null,null,null,null); while(cursor.movetonext()){ int _id=cursor.getint(cursor.getcolumnindex("_id")); string display_name=cursor.getstring(cursor.getcolumnindex("display_name")); log.i("test",_id+" "+display_name); uri uridata=uri.parse("content://com.android.contacts/raw_contacts/"+_id+"/data"); cursor cursordata=cr.query(uridata,null,null,null,null); while(cursordata.movetonext()){ string mimetype=cursordata.getstring(cursordata.getcolumnindex("mimetype")); string data1=cursordata.getstring(cursordata.getcolumnindex("data1")); if("vnd.android.cursor.item/phone_v2".equals(mimetype)){ log.i("test"," "+mimetype+" "+data1); } } } } }
xml部分:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.content.mainactivity"> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取手机联系人" android:onclick="getcontacts" /> </linearlayout>
在需要获取系统的东西的时候一定不要忘记给权限啊
androidmanifest.xml部分:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.content"> <!--获取手机的联系人--> <uses-permission android:name="android.permission.read_contacts"></uses-permission> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。