Permissions to make calls compatible with Android 6.0 and earlier versions

Question:

In my app, I am creating an Activity with several TextView that collects the information from a SQLite integrated in my app, and one of the data is the phone.

My intention with this data was to be able to create a button in the same Activity , which when pressed, will make the call to the phone of the database record that is shown on the screen, but I have found that for each version of Android it is done in a way, for example:

For Android 5.0:

Intent intent = new Intent(Intent.ACTION_CALL);         
intent.setPackage("com.android.phone");
intent.setData(Uri.parse("tel:" + number));
context.startActivity(intent);

But for Android 6.0 I have no idea how to do it and of course, it not only has to be for the latest version, but it has to be compatible with the others.

My question is:

How do I create a permission to be able to make calls compatible with Android 6.0 and earlier?

I hope you can give me a hand and an example. 🙂

Thanks to everyone beforehand.

Answer:

I leave you the example of the link developer.android.com/training/permissions/requesting.html that I just did taking advantage of the fact that I will also have to implement it.

Ask for permissions only from 6.0:

final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CALL_PHONE)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CALL_PHONE)) {

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

Receive the user's response:

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone();
            } else {
                System.out.println("El usuario ha rechazado el permiso");
            }
            return;
        }
    }
}

public void callPhone() {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setPackage("com.android.phone");
    intent.setData(Uri.parse("tel:" + number));
    context.startActivity(intent);
}

Tried it and it goes fine anyway now I'll also try @Elenasys example. All the best.

Scroll to Top