運(yùn)行時權(quán)限問題
- 以讀物聯(lián)系人為例,
1)有一個listView展示數(shù)據(jù)
2)擁有讀取聯(lián)系人的權(quán)限
3)讀取聯(lián)系人的數(shù)據(jù)
展示數(shù)據(jù)的布局文件和配置
<ListView
android:id="@+id/contract_listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
//配置listView
contacts = new ArrayList<>();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
listView.setAdapter(adapter);
判斷是否擁有權(quán)限
//判斷是否有權(quán)限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);//沒有的情況
}else {
readContacts();//有
}
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,"你拒絕了服務(wù).",Toast.LENGTH_SHORT).show();
}
}
}
讀取數(shù)據(jù)