Requesting Permission dialogue not showing up at all with this code, why?

Viewed 528

I am trying to request STORAGE Permission from the user at runtime after clicking a certain button. But somehow, this code (which is contained within a fragment's class) is not working at all no matter what I try.

binding.button.setOnClickListener {
    requestPermissions(this.requireActivity(), "android.permission.WRITE_EXTERNAL_STORAGE", 392)
}

This piece of code isn't working either for both write and read permissions :

binding.button.setOnClickListener {
    ActivityCompat.requestPermissions(this.requireActivity(), "android.permission.WRITE_EXTERNAL_STORAGE", 392)
}

No dialogue appears no matter what.

NOTE: I am testing on a physical device running on API 29. NOTE2: I added the permission both WRITE and READ permissions to the manifest. NOTE3: Performing any IO task crashes my app.

I looked up all over the internet but I still don't understand why it's not working.

1 Answers

As for your way for checking the permissions if it's inside a fragment maybe it's not correct , since these methods are deprecated and you may use another way which is the recommended one

Documentation for how to request permissions|android developers

which is the right way which goes as this:

Step 1 -You put this code as global in fragment/activity:

private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) doSomething()
                else
                    Toast.makeText(getContext(), "Can't continue without the required permissions", Toast.LENGTH_LONG).show();
            });

Step 2- Then when you need to request for a permission you call launch on the object you declared as global , which is to be called in the OnCreate() function of the Fragment / Activity .So if you want to ask these permissions at the creation of the fragment / Activity then just place this code in OnCreate() or if are using a button to check permission then set the onClickListener for the same in onCreate() function:

public void getNecessaryPermissionsAnddoSomething() {
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
        } else doSomething();
    }
Related