I'm developing an Android application to make a phone call. It gives me the following exception:
java.lang.SecurityException: Permission Denial: starting Intent {act = android.intent.action.CALL dat = tel: xxxxxxxxx cmp = com.android.server.telecom / .components.UserCallActivity} from ProcessRecord {1a0df5b 9112: (pid = 9112, uid = 10265) with revoked permission android.permission.CALL_PHONE
This occurs when you enter the if and pass the StartActivity line of the following code block:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNumTel = findViewById(R.id.edt_numero_telefone);
btnFazerChamada = findViewById(R.id.btn_fazer_chamada);
btnFazerChamada.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent it = new Intent(Intent.ACTION_CALL);
it.setData(Uri.parse("tel:"+edtNumTel.getText().toString()));
if (ActivityCompat.checkSelfPermission( MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
startActivity(it);
return;
}
}
});
I added the permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
And the following code block in Activity Main:
@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) {
Toast.makeText(getApplicationContext(), "Permissao aceite", Toast.LENGTH_SHORT).show();
}
}
}
}