最近開(kāi)發(fā)Android項(xiàng)目中遇到需要用到通訊錄的需求产弹,谷歌百度查了一下禾乘,根據(jù)自己的需求渊胸,利用ContentProvder的ContentResolver來(lái)獲取的通訊錄并封裝的一個(gè)工具類(lèi)ContactUtils
Demo效果圖:
源碼:
https://github.com/ok406lhq/ContactDemo
/**
* 獲取通訊錄工具類(lèi)
* 返回的數(shù)據(jù):
* [{
* "name": "xxx",
* "note": "呵呵呵呵",
* "phone": "13333333332"
* },
* {
* "name": "yyy",
* "phone": "13333333333"
* },
* {
* "name": "zzz",
* "phone": "13333333334"
* },
* ......
* ]
*/
public class ContactUtils {
public static ArrayList<MyContacts> getAllContacts(Context context) {
ArrayList<MyContacts> contacts = new ArrayList<MyContacts>();
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
//新建一個(gè)聯(lián)系人實(shí)例
MyContacts temp = new MyContacts();
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
//獲取聯(lián)系人姓名
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
temp.name = name;
//獲取聯(lián)系人電話號(hào)碼
Cursor phoneCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
while (phoneCursor.moveToNext()) {
String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phone = phone.replace("-", "");
phone = phone.replace(" ", "");
temp.phone = phone;
}
//獲取聯(lián)系人備注信息
Cursor noteCursor = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Nickname.NAME},
ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE + "'",
new String[]{contactId}, null);
if (noteCursor.moveToFirst()) {
do {
String note = noteCursor.getString(noteCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
temp.note = note;
Log.i("note:", note);
} while (noteCursor.moveToNext());
}
contacts.add(temp);
//記得要把cursor給close掉
phoneCursor.close();
noteCursor.close();
}
cursor.close();
return contacts;
}
}
bean類(lèi)MyContacts里包含了三個(gè)屬性:name瞬铸,phone,note(備注)经伙,這里就不貼代碼了扶叉,都是可以根據(jù)IDE自動(dòng)構(gòu)建的getter、setter和toString帕膜。
需要注意的點(diǎn)有幾個(gè):
一辜梳、權(quán)限問(wèn)題
在Android6.0版本加強(qiáng)了用戶的安全體驗(yàn),在2015年8月泳叠,Google發(fā)布了Android6.0版本作瞄,在用戶權(quán)限的選擇方面給了更靈活、更安全的操作方式危纫。要知道原先(6.0之前)的用戶對(duì)于權(quán)限的操作宗挥,只需要在安裝時(shí)點(diǎn)擊同意,所有權(quán)限就都給了种蝶,不然的話用戶只能選擇拒絕安裝契耿。也就是說(shuō),假如用戶不想App獲取通訊錄等隱私信息螃征,只能選擇不安裝應(yīng)用搪桂。6.0開(kāi)始,Google引入了權(quán)限申請(qǐng)機(jī)制盯滚,把權(quán)限分為危險(xiǎn)權(quán)限和正常權(quán)限踢械。
ok~科普結(jié)束。現(xiàn)在你要知道獲取通訊錄的權(quán)限是屬于危險(xiǎn)權(quán)限魄藕,需要?jiǎng)討B(tài)申請(qǐng)?jiān)摍?quán)限内列。
二、申請(qǐng)方法
在調(diào)用上述通訊錄工具類(lèi)之前背率,默認(rèn)是沒(méi)有權(quán)限的话瞧,需要?jiǎng)討B(tài)申請(qǐng)權(quán)限:
(1)首先在AndroidManifest.xml中添加所需權(quán)限
<uses-permission android:name="android.permission.READ_CONTACTS" />
(2)根據(jù)不同版本嫩与,封裝一個(gè)方法來(lái)檢查和申請(qǐng)權(quán)限
/**
* 動(dòng)態(tài)權(quán)限
*/
public void addPermissByPermissionList(Activity activity, String[] permissions, int request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //Android 6.0開(kāi)始的動(dòng)態(tài)權(quán)限,這里進(jìn)行版本判斷
ArrayList<String> mPermissionList = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
if (ContextCompat.checkSelfPermission(activity, permissions[i])
!= PackageManager.PERMISSION_GRANTED) {
mPermissionList.add(permissions[i]);
}
}
if (mPermissionList.isEmpty()) { //非初次進(jìn)入App且已授權(quán)
showContacts();
Toast.makeText(this, "已授權(quán)", Toast.LENGTH_SHORT).show();
} else {
//請(qǐng)求權(quán)限方法
String[] permissionsNew = mPermissionList.toArray(new String[mPermissionList.size()]);//將List轉(zhuǎn)為數(shù)組
ActivityCompat.requestPermissions(activity, permissionsNew, request); //這個(gè)觸發(fā)下面onRequestPermissionsResult這個(gè)回調(diào)
}
}
}
(3)重寫(xiě)onRequestPermissionsResult方法根據(jù)用戶的不同選擇做出響應(yīng)
/**
* requestPermissions的回調(diào)
* 一個(gè)或多個(gè)權(quán)限請(qǐng)求結(jié)果回調(diào)
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean hasAllGranted = true;
//判斷是否拒絕 拒絕后要怎么處理 以及取消再次提示的處理
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
hasAllGranted = false;
break;
}
}
if (hasAllGranted) { //同意權(quán)限做的處理,開(kāi)啟服務(wù)提交通訊錄
showContacts();
Toast.makeText(this, "同意授權(quán)", Toast.LENGTH_SHORT).show();
} else { //拒絕授權(quán)做的處理交排,彈出彈框提示用戶授權(quán)
dealwithPermiss(MainActivity.this, permissions[0]);
}
}
引導(dǎo)處理權(quán)限拒絕之后的操作:
public void dealwithPermiss(final Activity context, String permission) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("操作提示")
.setMessage("注意:當(dāng)前缺少必要權(quán)限划滋!\n請(qǐng)點(diǎn)擊“設(shè)置”-“權(quán)限”-打開(kāi)所需權(quán)限\n最后點(diǎn)擊兩次后退按鈕,即可返回")
.setPositiveButton("去授權(quán)", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", context.getApplicationContext().getPackageName(), null);
intent.setData(uri);
context.startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "取消操作", Toast.LENGTH_SHORT).show();
}
}).show();
}
}
Ps
當(dāng)然你也可以使用RxPermission埃篓,這里有篇博客可以參考一下