本文實例為大家分享了Android讀取手機通訊錄聯系人到項目的具體代碼,供大家參考,具體內容如下
一、主界面代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" > < ListView android:id = "@+id/contacts_view" android:layout_width = "match_parent" android:layout_height = "match_parent" > </ ListView > </ LinearLayout > |
簡單的添加了一個listview來展示待會讀取到的通訊錄數據。
二、MainAcitivity代碼如下,代碼中有詳細注釋!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
public class MainActivity extends AppCompatActivity { ArrayAdapter<String> adapter; List<String> contactsList= new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取到listview并且設置適配器 ListView contactsView= (ListView) findViewById(R.id.contacts_view); adapter= new ArrayAdapter<String>( this ,android.R.layout.simple_list_item_1,contactsList); contactsView.setAdapter(adapter); //判斷是否開啟讀取通訊錄的權限 if (ContextCompat.checkSelfPermission( this , Manifest.permission.READ_CONTACTS)!= PackageManager .PERMISSION_GRANTED){ ActivityCompat.requestPermissions( this , new String[]{Manifest.permission.READ_CONTACTS}, 1 ); } else { readContacts(); } } private void readContacts() { Cursor cursor= null ; try { //查詢聯系人數據,使用了getContentResolver().query方法來查詢系統的聯系人的數據 //CONTENT_URI就是一個封裝好的Uri,是已經解析過得常量 cursor=getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null , null , null , null ); //對cursor進行遍歷,取出姓名和電話號碼 if (cursor!= null ){ while (cursor.moveToNext()){ //獲取聯系人姓名 String displayName=cursor.getString(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME )); //獲取聯系人手機號 String number=cursor.getString(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER )); //把取出的兩類數據進行拼接,中間加換行符,然后添加到listview中 contactsList.add(displayName+ "\n" +number); } //刷新listview adapter.notifyDataSetChanged(); } } catch (Exception e){ e.printStackTrace(); } finally { //記得關掉cursor if (cursor!= null ){ cursor.close(); } } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int [] grantResults) { switch (requestCode){ case 1 : if (grantResults.length> 0 &&grantResults[ 0 ]==PackageManager.PERMISSION_GRANTED){ readContacts(); } else { Toast.makeText( this , "沒有權限" ,Toast.LENGTH_SHORT).show(); } break ; default : break ; } } } |
三、由于讀取通訊錄屬于危險權限,所以記得在Manifest中開啟權限
1
|
<uses-permission android:name= "android.permission.READ_CONTACTS" /> |
好了,下面運行一下,就可以讀取出你手機里面的通訊錄數據了!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/MagicMHD/article/details/80863913