Android6.0动态权限申请

时间:2022-01-14 15:24:44
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:{
call();
break;
}
}
}
private boolean checkp(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED) {

//如果拒绝过 true
//如果不再询问 FALSE
//如果设备禁止应用拥有此权限,FALSE
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("its important")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 2);
}
}).create();
dialog.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE,Manifest.permission.READ_CALL_LOG}, 2);
}
return false;
}
return true;
}

private void call(){
Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:888"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (checkp())
startActivity(intent);
}

//数组和请求的顺序对应
//如果取消 result为空
//如果已经授权了同一组的某个权限 自动授权
//如果已经不再询问 自动拒绝
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==2){
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
call();
}
}
}
}
  <uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>