domingo, 11 de outubro de 2015

Permissions no Android

Pessoal, hoje, na minha app Android, eu estava tentando fazer uma ligação. Dessa forma:

    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:456"));
        startActivity(intent);
    }


Mas deu o erro:

Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{3e464e1 3861:br.com.localhost8080.myapp/u0a62} (pid=3861, uid=10062) requires android.permission.CALL_PHONE

Então fui no AndroidManifest.xml e coloquei a permission:

        <uses-permission android:name="android.permission.CALL_PHONE"/>


Mas aí aconteceu o erro:

Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{ea870e6 4476:br.com.localhost8080.myapp/u0a62} (pid=4476, uid=10062) with revoked permission android.permission.CALL_PHONE

Para resolver usei o código abaixo pois a permission CALL_PHONE é level dangerous e você precisa solicitar permissao para o usuário:

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;

    public void onClick(View view) {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            callPhone();
        }
    }

    @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();
                }
            }
        }
    }

    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:456"));
        startActivity(intent);
    }

Mais detalhes sobre permissões no android: https://developer.android.com/training/permissions/index.html

Mais detalhes sobre esse processo de ter que solicitar permissões: https://developer.android.com/training/permissions/requesting.html

Nenhum comentário:

Postar um comentário