Android Studio 学习(六)内容提供器

运行时权限

  • 使用ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED//判断是否有权限
  • ActivityCompat.requestPermissions(MainActivity.this,
    new String[] {Manifest.permission.CALL_PHONE},1);//没有权限 进行申请
  • onRequestPermissionResult() //无论哪种结果都会回调到这个函数中 所以重写这个函数

makecallButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.CALL_PHONE},1);
else
call();
}
});
private void call()
{
try{
Intent intent = new Intent (Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
catch (SecurityException e)
{
e.printStackTrace();
}
}

@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)
            call();
        else
            Toast.makeText(MainActivity.this,"you denied the  permission",Toast.LENGTH_LONG).show();
        break;
    default:
}
}

}

查找联系人姓名和电话

ListView contactsView = (ListView) findViewById(R.id.listview);
adapter = new ArrayAdapter(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},2);
else {
readContanct();
}

private void readContanct()
{
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.getColumnName(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(number);
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if(cursor!=null)
cursor.close();
}
}

原文地址:https://www.cnblogs.com/lancelee98/p/9486283.html