Runtime permissions on android

0

I have a code in android studio that asks the user, permission to use the phone service (to get the imei)

Well, my code is working perfectly, with a problem, when entering the page, a message is displayed if the permission was not conceived, until here, everything ok, but after the user accepts the permission, as I identify it was I accept and then yes, follow 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 gets done, and only loads the information after I leave and enter it again, how would I solve this?

    
asked by anonymous 19.12.2017 / 07:03

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 # of the application with the results.

  • p>

    To verify that the user gave the permission, you need to override 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();
                    }
                }
            }
        }
    }
    
        
  • 19.12.2017 / 08:10