android – Runtime permissions: onRequestPermissionsResult is getting called without prompting the user-ThrowExceptions

Exception or error:

I am facing a very strange problem for the very first time. The problem is that I need some permissions at runtime. I am using the below code to get runtime permissions.

 private void askForPermissions() {
    if (!PermissionUtility.hasPermissions(this, mLoginViewModel.getPermissions())) {
        ActivityCompat.requestPermissions(this, mLoginViewModel.getPermissions(), LoginViewModel.CODE_PERMISSION_ALL);
    }
}

And this is where I intercept the user’s grant or denial.

  @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == LoginViewModel.CODE_PERMISSION_ALL) {
        for (int a = 0; a < permissions.length; a++) {
            if (grantResults[a] == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "Permissions are mandatory to continue app", Toast.LENGTH_LONG).show();
                askForPermissions();
                return;
            }
        }
    }
}

Here is the interesting thing. When I call askForPermissions(), it automatically calls onRequestPermissionsResult(). The key point is that no dialog is shown, so the user is not granting nor declining permissions. Why on earth onRequestPermissionsResult() is being called?

Below is the code of onCreate() where I am calling askForPermissions().

   @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    askForPermissions();
}

Any help??

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *