Runtime permissions on android

Asked

Viewed 781 times

0

I have a code in android studio that asks the user, permission to use the phone service (to pick up Imei)

well, my code is working perfectly, with a problem, when entering the page, a message is displayed if the permission was not conceived, so far, everything ok , but after the user accepts the permission, as I identify that it was accepted and then yes, follows the code?

my code :

  checkedPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE);

    if (Build.VERSION.SDK_INT >= 23 && checkedPermission != PackageManager.PERMISSION_GRANTED) {
        showMessageOKCancel("É nescesssario ter Acesso a Informaçoes do Aparelho Para Obter Melhor Desempenho!",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissions(new String[] {Manifest.permission.READ_PHONE_STATE},
                                REQUEST_CODE_PHONE_STATE_READ);
                    }
                });
        return ;
    } else
        checkedPermission = PackageManager.PERMISSION_GRANTED;

after the user accepts the permission, my Activity is done, and only loads the information after I leave and enter it again, as it would solve this?

1 answer

3

The permission system android is asynchronous: it returns immediately and, after the user responds to the dialog box, the system calls the method onRequestPermissionsResult of the application with the results.

To verify that the user has given permission, it is necessary to replace this method in your Activity

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_CODE_PHONE_STATE_READ) {
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults.length > 0
                && grantResults[i] == PackageManager.PERMISSION_GRANTED
            ) {
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

                if (telephonyManager != null) {
                    Toast.makeText(this, "Imei: ".concat(telephonyManager.getDeviceId()), Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.