"java.lang.SecurityException: Permission Denial" on Android 6 Marshmallow (API 23)

11

I'm trying to register a broadcastreceiver so I can check out a new sms that might arrive on the device.

I'm getting an error only in android marshmallow in the following snippet of code from my fragment:

    public static final String BROADCAST = "android.provider.Telephony.SMS_RECEIVED";
    .
    .
    .
    Intent intent = new Intent(BROADCAST);
    getActivity().sendBroadcast(intent);//erro nessa linha

Error:

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.provider.Telephony.SMS_RECEIVED from pid=10506, uid=10064
    
asked by anonymous 30.03.2016 / 22:28

1 answer

12

As of version 6.0 (API level 23), the permissions considered "dangerous" ( Dangerous permissions ) are validated during application execution and not when installing. This does not invalidate that they do not have to be declared in AndroidManifest.xml .

Apps with targetApi 23+ that require Dangerous permissions , to run on Android 6.0+ devices will have to adjust to this new approach.

Whenever the application performs an operation that requires a permission of this type, it must verify that it has it before running it.

This check is done by calling the ContextCompat.checkSelfPermission () :

int permissionCheck = ContextCompat.checkSelfPermission(context,
                                                        Manifest.permission.RECEIVE_SMS);

If the application has the permission it is returned PackageManager.PERMISSION_GRANTED otherwise it returns PackageManager.PERMISSION_DENIED

If the application does not have the permission, you need to request it using the ActivityCompat.requestPermissions () :

private final int PERMISSIONS_REQUEST_RECEIVE_SMS = 1;
ActivityCompat.requestPermissions(context,
                                  new String[]{Manifest.permission.RECEIVE_SMS},
                                  PERMISSIONS_REQUEST_RECEIVE_SMS);

A dialog will then be opened asking the user for permission. The dialog is shown asynchronously, with the onRequestPermissionsResult() method called when the user responds.

This method should be implemented to handle the response:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_RECEIVE_SMS: {
            // Se o pedido foi cancelado o array está vazio.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permissão foi concedida
                // pode fazer o que pretende

            } else {

                // permissão foi negada

            }
            return;
        }

        // outros 'case' se tiver outras permissões para verificar
    }
}

For more detailed information, see the documentation .

    
30.03.2016 / 23:36