Błąd uprawnień do przechowywania w Marshmallow

159

W Lollipop, funkcja pobierania działa dobrze w mojej aplikacji, ale kiedy zaktualizowałem do Marshmallow, moja aplikacja ulega awarii i wyświetla ten błąd, gdy próbuję pobrać z Internetu na kartę SD:

Neither user  nor current process has android.permission.WRITE_EXTERNAL_STORAGE

Narzeka na ten wiersz kodu:

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

Mam uprawnienia w manifeście poza aplikacją:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Wyczyściłem i odbudowałem projekt, ale nadal się zawiesza.

Badr
źródło
Spróbuj tego, co może ci pomóc: - stackoverflow.com/a/41221852/5488468
Bipin Bharti
Przygotowałem bibliotekę, która pomoże w łatwej obsłudze uprawnień runtime. github.com/nabinbhandari/Android-Permissions
Nabin Bhandari

Odpowiedzi:

357

Należy sprawdzić, czy użytkownik przyznał uprawnienia do przechowywania zewnętrznego za pomocą:

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    Log.v(TAG,"Permission is granted");
    //File write logic here
    return true;
}

Jeśli nie, musisz poprosić użytkownika o przyznanie aplikacji uprawnienia:

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

Oczywiście są one przeznaczone tylko dla urządzeń Marshmallow, więc musisz sprawdzić, czy Twoja aplikacja działa na Marshmallow:

 if (Build.VERSION.SDK_INT >= 23) {
      //do your check here
 }

Upewnij się również, że Twoja działalność się realizuje OnRequestPermissionResult

Całe pozwolenie wygląda następująco:

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

Wywołanie zwrotne wyniku uprawnień:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}
MetaSnarf
źródło
2
@Houssem chętnie pomogę.!
MetaSnarf
14
To nie działa dla API> = 23, żądanie pozwolenia na Manifest.permission.WRITE_EXTERNAL_STORAGEzawsze zwraca „-1”, tj. Odmowa dostępu. Sprawdź nową dokumentację, która mówi, że od API 19 nie potrzebujesz WRITE_EXTERNAL_STORAGEpozwolenia. Jak wspomniano w niektórych z powyższych komentarzy, powinieneś zrobić to wszystko zManifest.permission.READ_EXTERNAL_STORAGE
AmeyaB
3
@VSB: Jest w dziwnym miejscu, ale proszę bardzo: developer.android.com/guide/topics/manifest/ ...
AmeyaB
3
@AmeyB Jak wspomniano w dokumentacji, dla API> = 19, uprawnienia do zapisu w pamięci zewnętrznej nie muszą być deklarowane, JEŚLI aplikacja będzie używać własnego katalogu na pamięci zewnętrznej, który jest zwracany przez getExternalFilesDir(). W innych przypadkach zezwolenie android.permission.WRITE_EXTERNAL_STORAGEmusi być zadeklarowane w sposób najbardziej zrozumiały.
VSB
1
Tak, naprawiono. Problem był związany z biblioteką aplikacji hokejowych. ta biblioteka zastąpiła moje uprawnienia do zapisu. @MetaSnarf
Selin
38

System uprawnień Androida jest jednym z największych problemów związanych z bezpieczeństwem, ponieważ te uprawnienia są wymagane w czasie instalacji. Po zainstalowaniu aplikacja będzie mogła uzyskać dostęp do wszystkich przyznanych rzeczy bez wiedzy użytkownika, co dokładnie robi aplikacja z uprawnieniem.

Android 6.0 Marshmallow wprowadza jedną z największych zmian w modelu uprawnień, dodając uprawnienia środowiska uruchomieniowego, nowy model uprawnień, który zastępuje istniejący model uprawnień dotyczący czasu instalacji, gdy docelowy interfejs API 23 jest docelowy, a aplikacja działa na urządzeniu z systemem Android 6.0+

Dzięki uprzejmości przejdź do sekcji Proszenie o uprawnienia w czasie wykonywania .

Przykład

Zadeklaruj to jako globalne

private static final int PERMISSION_REQUEST_CODE = 1;

Dodaj to w swojej onCreate()sekcji

Po setContentView (R.layout.your_xml);

 if (Build.VERSION.SDK_INT >= 23)
    {
        if (checkPermission())
        {
            // Code for above or equal 23 API Oriented Device 
            // Your Permission granted already .Do next code
        } else {
            requestPermission(); // Code for permission
        }
    }
  else
    {

       // Code for Below 23 API Oriented Device 
       // Do next code
    }

Teraz dodajemy checkPermission () i requestPermission ()

 private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

private void requestPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        Toast.makeText(Your_Activity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
    } else {
        ActivityCompat.requestPermissions(Your_Activity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("value", "Permission Granted, Now you can use local drive .");
            } else {
                Log.e("value", "Permission Denied, You cannot use local drive .");
            }
            break;
    }
}

FYI

onRequestPermissionsResult

Ten interfejs jest umową dotyczącą otrzymywania wyników wniosków o pozwolenie.

IntelliJ Amiya
źródło
29

Sprawdź wiele uprawnień na poziomie API 23 Krok 1:

 String[] permissions = new String[]{
        Manifest.permission.INTERNET,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.VIBRATE,
        Manifest.permission.RECORD_AUDIO,
};

Krok 2:

 private boolean checkPermissions() {
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p : permissions) {
        result = ContextCompat.checkSelfPermission(this, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
        return false;
    }
    return true;
}

Krok 3:

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == 100) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // do something
        }
        return;
    }
}

Krok 4: w onCreate of Activity checkPermissions ();

Bipin Bharti
źródło
2
Dzięki. Wygląda to na obiecującą odpowiedź na wiele uprawnień. Ale brakuje trochę przykładów. Jak radzi sobie z never ask againkilkoma uprawnieniami i ich brakuje? Czy użytkownik otrzymuje jakieś uwagi? Byłoby miło zobaczyć prawdziwy przykład tego lub więcej komentarzy na temat fragmentów kodu.
not2qubit
Aby sobie z tym poradzić, nie pytaj ponownie, otaczaj dodawanie do uprawnień, jeśli blokuje się za pomocą if (shouldshowpermissionrationale ()) {} ... to prawda, jeśli pozwolenie jest potrzebne i nie jest na zawsze odrzucone
me_
Ta odpowiedź powinna być poprawna i zoptymalizowana.
VikaS GuttE
21

O ile nie ma wyraźnego wymogu zapisywania w pamięci zewnętrznej, zawsze możesz zapisać pliki w katalogu aplikacji. W moim przypadku musiałem zapisywać pliki i po zmarnowaniu 2 do 3 dni dowiedziałem się, czy zmieniam ścieżkę przechowywania z

Environment.getExternalStorageDirectory()

do

getApplicationContext().getFilesDir().getPath() //which returns the internal app files directory path

działa jak urok na wszystkich urządzeniach. Dzieje się tak, ponieważ do pisania w pamięci zewnętrznej potrzebujesz dodatkowych uprawnień, ale pisanie w wewnętrznym katalogu aplikacji jest proste.

Mujtaba Hassan
źródło
gdzie piszesz ten kod? Nie pamiętam użyciu Environment.getExternalStorageDiretory () na mój kod
royjavelosa
5

musisz użyć uprawnienia runtime w marshmallow https://developer.android.com/training/permissions/requesting.html

możesz sprawdzić informacje o aplikacji -> uprawnienia

czy Twoja aplikacja ma uprawnienia do zapisu w pamięci zewnętrznej, czy nie

aiwiguna
źródło
2
faktycznie ta odpowiedź aplikacja informacje -> pozwolenie rozwiązało awarię :), ale zaakceptowałem drugą odpowiedź, aby dowiedzieć się, co robić. Żałuję, że nie mogę przyjąć obu. Dziękuję bardzo
Badr
Dzięki temu naprawiono problem z awarią przeglądarki podczas pobierania w emulatorze Androida
sdaffa23fdsf
4

Wygląda na to, że użytkownik odmówił pozwolenia, a aplikacja próbuje zapisać na dysku zewnętrznym, powodując błąd.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Sprawdź https://developer.android.com/training/permissions/requesting.html

Ten film daje lepsze wyobrażenie o UX, obsłudze uprawnień Runtime https://www.youtube.com/watch?v=iZqDdvhTZj0

VenomVendor
źródło
1

Od wersji marshmallow programiści muszą prosić użytkownika o uprawnienia do wykonania. Pozwólcie, że przedstawię wam cały proces zadawania uprawnień w czasie wykonywania.

Używam odniesienia stąd: uprawnienia runtime marshmallow android .

Najpierw utwórz metodę, która sprawdza, czy wszystkie uprawnienia są nadane, czy nie

private  boolean checkAndRequestPermissions() {
        int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int writepermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permissionLocation = ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionRecordAudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);


        List<String> listPermissionsNeeded = new ArrayList<>();

        if (camerapermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }
        if (writepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (permissionRecordAudio != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    } 

Oto kod, który jest uruchamiany po powyższej metodzie. ZastąpimyonRequestPermissionsResult() metodę:

 @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        Log.d(TAG, "Permission callback called-------");
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                Map<String, Integer> perms = new HashMap<>();
                // Initialize the map with both permissions
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                // Fill with actual results from user
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    // Check for both permissions
                    if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                            && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED 
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
&& perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "sms & location services permission granted");
                        // process the normal flow
                        Intent i = new Intent(MainActivity.this, WelcomeActivity.class);
                        startActivity(i);
                        finish();
                        //else any one or both the permissions are not granted
                    } else {
                        Log.d(TAG, "Some permissions are not granted ask again ");
                        //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
//                        // shouldShowRequestPermissionRationale will return true
                        //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) 
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) 
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
 || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                            showDialogOK("Service Permissions are required for this app",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                                case DialogInterface.BUTTON_POSITIVE:
                                                    checkAndRequestPermissions();
                                                    break;
                                                case DialogInterface.BUTTON_NEGATIVE:
                                                    // proceed with logic by disabling the related features or quit the app.
                                                    finish();
                                                    break;
                                            }
                                        }
                                    });
                        }
                        //permission is denied (and never ask again is  checked)
                        //shouldShowRequestPermissionRationale will return false
                        else {
                            explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                            //                            //proceed with logic by disabling the related features or quit the app.
                        }
                    }
                }
            }
        }

    }

Jeśli użytkownik kliknie opcję Deny , showDialogOK()metoda zostanie użyta do wyświetlenia okna dialogowego

Jeśli użytkownik kliknie Odmów, a także kliknie pole wyboru z informacją „nigdy więcej nie pytaj” , explain()metoda zostanie użyta do wyświetlenia okna dialogowego.

metody wyświetlania okien dialogowych:

 private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", okListener)
                .create()
                .show();
    }
    private void explain(String msg){
        final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
        dialog.setMessage(msg)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        //  permissionsclass.requestPermission(type,code);
                        startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:com.exampledemo.parsaniahardik.marshmallowpermission")));
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.show();
    }

Powyższy fragment kodu prosi o podanie czterech uprawnień naraz. Możesz również poprosić o dowolną liczbę uprawnień w dowolnej działalności zgodnie z własnymi wymaganiami.

user6435056
źródło
0

Po wielu poszukiwaniach ten kod działa dla mnie:

Sprawdź, czy uprawnienie już ma: Sprawdź uprawnienia WRITE_EXTERNAL_STORAGE Dozwolone czy nie?

if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            //Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }else{
            requestStoragePermission();
        }



private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

Implementuj Override onRequestPermissionsResult do sprawdzania, czy użytkownik zezwala lub odmawia

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //Checking the request code of our request
    if(requestCode == REQUEST_WRITE_STORAGE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();

        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
        }
    }
Tariqul
źródło
0

to działa dla mnie

 boolean hasPermission = (ContextCompat.checkSelfPermission(AddContactActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(AddContactActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

   @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(AddContactActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}
RejoylinLokeshwaran
źródło
0
   Try this



int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

     if (permission != PackageManager.PERMISSION_GRANTED) {
                Log.i("grant", "Permission to record denied");

                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage(getString(R.string.permsg))
                            .setTitle(getString(R.string.permtitle));

                    builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                            Log.i("grant", "Clicked");
                            makeRequest();
                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();

                } else {

                    //makeRequest1();
                    makeRequest();
                }
            }


     protected void makeRequest() {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    500);
        }



     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 500: {

                    if (grantResults.length == 0
                            || grantResults[0] !=
                            PackageManager.PERMISSION_GRANTED) {

                        Log.i("1", "Permission has been denied by user");

                    } else {

                        Log.i("1", "Permission has been granted by user");

                    }
                    return;
                }

            }
        }
Makvin
źródło
0

Przed rozpoczęciem pobierania sprawdź uprawnienia środowiska uruchomieniowego, a jeśli nie masz uprawnień, poproś o uprawnienia, takie jak ta metoda

requestStoragePermission ()

private void requestStoragePermission(){
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
                android.Manifest.permission.READ_EXTERNAL_STORAGE))
        {

        }

        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            STORAGE_PERMISSION_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, 
                @NonNull String[] permissions, 
                @NonNull int[] grantResults) {

    if(requestCode == STORAGE_PERMISSION_CODE){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        }
        else{
            Toast.makeText(this,
                           "Oops you just denied the permission", 
                           Toast.LENGTH_LONG).show();
        }
    }
}
Balaji Rajendran
źródło
0

W prosty sposób pozwolenie można nadać za pomocą pliku manifest.xml, ale było ok do poziomu api 23 sdk w wersji 6, po tym, jak chcemy uzyskać pozwolenie, musimy poprosić o użycie, aby zezwolić które są potrzebne.

Po prostu dodaj ten kod do pliku mainActivity.java

Override
            public void onClick(View view) {
                // Request the permission
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.CAMERA},
                        PERMISSION_REQUEST_CAMERA);

Jeśli chcesz, zamień CAMERA lub dodaj WRITE_EXTERNAL_STORAGE z unikalnym kodem.

                            new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    101);

To jest prosty kod do uzyskania pozwolenia.

Pravin Ghorle
źródło