Request permission to access Android internal storage by a Fragment

1

How do I request permission to access the device's internal storage by a Fragment?

In normal activity I used this code:

int REQUEST_CODE = 0;
ActivityCompat.requestPermissions(MainActivity.this, new String[] 
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
    
asked by anonymous 29.08.2018 / 17:09

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);


    }

If 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: link

    
29.08.2018 / 21:55