Request permission to access Android internal storage by a Fragment

Asked

Viewed 760 times

1

How do I make to request permission to access internal storage of the apparatus by a Fragment?

In the normal Activity I used that code:

int REQUEST_CODE = 0;
ActivityCompat.requestPermissions(MainActivity.this, new String[] 
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

1 answer

0

The class Fragment(android.support.v4.app.Fragment) has a method requestPermissions(@NonNull String[] permissions, int requestCode)

Example:

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        int REQUEST_CODE = 0;
        requestPermissions(new String[]
                {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

    }


    // Sobrescrever método para receber resultado das permissões
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    }

In case you want to check a permission on Fragment, you can use:

if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE
            );
        } else {
            // permissão concedida
        } 

Reference: https://stackoverflow.com/a/45353688/4181975

Browser other questions tagged

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