简体   繁体   中英

Why isn't my Android app asking the user to allow storage permissions when I wrote the necessary code in the onCreate method?

I am creating an MP3 player android app. The app needs to read external storage to get the MP3 files to play.

I have included the <uses-sdk...> tag for this permission (READ_EXTERNAL_STORAGE) in the android manifest file.

I also tried typing the following lines of code (separately) at the start of the onCreate method (below setTitle). code snippet 1 - the World - Hello message is logged

code snippet 2 - the Test-Hi message is logged However, the app won't ask user to allow storage access. I have to do it manually in settings. I tried resetting all apps but that didn't work. Other apps that need storage permission are asking for it successfully when the app is launched. I'm not sure why that's not the case for this app.

Help would be appreciated.

You need to declare permission in your manifest file also, then it will ask. Declare like this in manifest file

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

You can simply use this library to do it. It also very small.

  1. implementation 'com.karumi:dexter:6.2.3' add it to your root level build.gradle.

  2. Once it is synced, add these lines of code

    Dexter.withContext(context).withPermission(Manifest.permission.READ_EXTERNAL_SORAGE).withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) { Toast.makeText(this, "granted", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) { Toast.makeText(this, "denied", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) { permissionToken.continuePermissionRequest(); } }).check();

Tada. It's done.

Note: If you once deny the permission, you might not see the permission dialog again because android will think that you are troubling the user by again and again asking fro permission.In this case, the user needs to enable the permission from the settings.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM