Search code examples
androidandroid-studiopermissionsandroid-11

How To Ask For User Consent In Android 11


It works perfectly fine for android 10 but does not work in android 11 after some research I found out that we must ask for user consent, so I have gone through some video and I didn't understand how to so can anyone help me out here!

           File file = new File(childItem.getPath());

                file.delete();
                if (file.exists()) {
                    try {
                        file.getCanonicalFile().delete();
                        if (file.exists()) {
                            deleteFile(file.getName());
                        }
                    } catch (IOException unused) {
                        unused.printStackTrace();
                    }
                }

Solution

  • For Andorid11; you need user-interaction for modify or delete any files from external storage. You need to use createDeleteRequest for deletion of file. You can follow this steps:

    if (SDK_INT >= Build.VERSION_CODES.R) {
      List<Uri> uris = new ArrayList<>();
      
      // Your for loop starts here, if you want to delete multiple files..
      
    // for(File childItem : yourFileList){
    
          long mediaID = getFilePathToMediaID(childItem.getPath(), MainActivity.this);
          Uri Uri_one = ContentUris.withAppendedId(MediaStore.Images.Media.getContentUri("external"), mediaID);
          uris.add(Uri_one);
         // } /*for ends here */
            
                 requestDeletePermission(MainActivity.this, uris);
    }
    

    now create delete request like this;

     private static final int REQUEST_PERM_DELETE = 444;
    
        @RequiresApi(api = Build.VERSION_CODES.R)
        private void requestDeletePermission(Context context, List<Uri> uri_one) {
            PendingIntent pi = MediaStore.createDeleteRequest(context.getContentResolver(), uri_one);
            try {
                startIntentSenderForResult(pi.getIntentSender(), REQUEST_PERM_DELETE, null, 0, 0, 0);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
    

    now handle result in your onActivityResult ;

     @Override
        public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
           
            switch (requestCode) {
                case REQUEST_PERM_DELETE:
                    if (resultCode == Activity.RESULT_OK) {
                        Toast.makeText(MainActivity.this, "Deleted successfully! Refreshing...", Toast.LENGTH_SHORT).show();
                          
                    } else {
                        Toast.makeText(MainActivity.this, "Failed to delete!", Toast.LENGTH_SHORT).show();
                    }
                    break;
    
            }
        }
    
     public static long getFilePathToMediaID(String songPath, Context context) {
            long id = 0;
            ContentResolver cr = context.getContentResolver();
    
            Uri uri = MediaStore.Files.getContentUri("external");
            String selection = MediaStore.Audio.Media.DATA;
            String[] selectionArgs = {songPath};
            String[] projection = {MediaStore.Audio.Media._ID};
            String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
    
            Cursor cursor = cr.query(uri, projection, selection + "=?", selectionArgs, null);
    
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
                    id = Long.parseLong(cursor.getString(idIndex));
                }
            }
    
            return id;
        }
    

    I hope this helps you.