MainActivity.kt代码
package com.example.fredric.readcontacts
import android.Manifest
import android.content.pm.PackageManager
import android.database.Cursor
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
var adapter: ArrayAdapter? = null
var contactsList = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var contactsView = findViewById(R.id.contacts_view)
adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,contactsList)
contactsView.adapter = adapter
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS),1)
} else {
readContacts()
}
}
fun readContacts() {
var cursor: Cursor? = null
try{
cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null)
if(cursor != null) {
while(cursor.moveToNext()) {
var displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
var number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
contactsList.add(displayName+"\n"+number)
}
adapter?.notifyDataSetChanged()
}
}catch (e: Exception) {
e.printStackTrace()
}finally {
if(cursor != null) {
cursor.close()
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
when(requestCode) {
1->{
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts()
}else {
Toast.makeText(this,"You denied the permission!!",Toast.LENGTH_SHORT).show()
}
}
else->{
}
}
}
}
activity_main.xml-->代码
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
android:id="@+id/contacts_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
AndroidManifest.xml文件代码:
package="com.example.fredric.readcontacts">
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">
成功效果:
Screen Shot 2018-07-19 at 6.22.31 AM.png