In this article, I will show you how to check and ask for storage permission.
You usually don’t need this permission if your app goes on Play Store.
Declear permission
1
| <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
Check and ask for permission
Environment.isExternalStorageManager()
only available after VERSION_CODES.R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class YourActivity { private fun checkPlatformPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Environment.isExternalStorageManager()) { setupAfterPermissionChecked() } else { check30AndAfter() } } else { setupAfterPermissionChecked() } }
@RequiresApi(api = Build.VERSION_CODES.R) private fun check30AndAfter() { try { Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { addCategory("android.intent.category.DEFAULT") data = Uri.parse("package:${applicationContext.packageName}") startActivityForResult(this, REQUEST_CODE_ALL_FILE_ACCESS) } } catch (e: Exception) { Intent().apply { action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION startActivityForResult(this, REQUEST_CODE_ALL_FILE_ACCESS) } } }
protected override fun onActivityResult( requestCode: Int, resultCode: Int, @Nullable data: Intent? ) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_ALL_FILE_ACCESS) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Environment.isExternalStorageManager()) { setupAfterPermissionChecked() } else { checkPlatformPermission() } } } }
fun setupAfterPermissionChecked() { }
companion object { private const val REQUEST_CODE_ALL_FILE_ACCESS = 404 } }
|
Reference
Manage all files on a storage device
File.listFiles() is returning null in android 11