Call Permission Not Working - How do you make a phone call in app for Android Studio?

ZachGiovanelli :
    public void onClick(View view) {

        if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            Log.d("STATE", "Call Button DOES NOT WORK");
            return;
        }
                Log.d("STATE", "Call Button DOES WORK");
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:480-240-9255"));
                startActivity(callIntent);

This code above keeps logging in the console that it does not work but I have the uses-permission for CALL_PHONE in my manifest file. I am not sure of any other permissions I would need or if the code is just incorrect? Please help, thank you.

A_Singh7 :

So, if the permission is there then it's ok, but what if the permission is not there ?

Then, you need to request the permissions using requestPermissions()

Something like:-

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode)

Then, override the method onRequestPermissionsResult(), to perform the required actions after the permission is granted (here you can start the activity using intent to make a phone call).

So you could do something like :-

int requestCode = 0;
public void onClick(View view) 
{ 
if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
 { 
Log.d("STATE", "Call Button DOES NOT WORK"); 
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode);
return;
 }
 Log.d("STATE", "Call Button DOES WORK"); 
Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setData(Uri.parse("tel:480-240-9255"));
 startActivity(callIntent);

}

Then,

@Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
if (requestCode == requestCode) 
{ 
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{ 
 Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setData(Uri.parse("tel:480-240-9255"));
 startActivity(callIntent);
}
 }

So, this code will give the user a pop-up stating that does the device have access to make or receive phone calls. If you grant the permission, the call manger activity would be started.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=378715&siteId=1