野生大熊猫

安卓权限问题以及读取系统联系人
读取联系人是需要系统权限的。首先我们AndroidManifest中添加权限。<manifest xmlns...
扫描右侧二维码阅读全文
16
2018/07

安卓权限问题以及读取系统联系人

读取联系人是需要系统权限的。
首先我们AndroidManifest中添加权限。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.contactstest">

    <uses-permission android:name="android.permission.READ_CONTACTS"/>
...
</manifest>

这里我们使用的是ListView,指定ListView的id为contacts_view

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 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){
//没有权限的话就申请权限,通过返回1,回调到onRequestPermissionsResult
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else {
//有权限直接显示
            readContacts();
        }
    }

//显示联系人
    private void readContacts() {
        Cursor cursor = null;
        try{
            //查询联系人
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
            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));
                    contactsList.add(displayName + "\n" + number);
                }
                adapter.notifyDataSetChanged();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
    }
//权限申请的回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
值如果为1,那么就直接显示
        switch(requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    readContacts();
                }else {
                    Toast.makeText(this,"你没有权限使用",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}
Last modification:July 20th, 2018 at 12:23 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment