skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. try this:

    Step 1

    private void get_files_to_delete() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                List<Uri> uri_list = new ArrayList<>();
    
    //            File my_folder = new File(Environment.getExternalStorageDirectory().getPath()+"/"+"Your folder");
    
                File my_single_file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+"Your folder"+"/"+"example.mp3");
    
    //            File[] list_fil = my_folder.listFiles();
    
           // Your for loop starts here, if you want to delete multiple files..
    
    //            for (File childItem : list_fil) {
                
                    if (my_single_file.exists()) {
                        Uri Uri_one = getFilePathToMediaID(my_single_file.getPath(), MainActivity.this);
                        uri_list.add(Uri_one);
                    }
                    
    //            }  /*for ends here */
    
    
                requestDeletePermission(MainActivity.this, uri_list);
            }
        }
    

    Step 2

    private Uri getFilePathToMediaID(String path, Context context) {
            
            Uri contentUri = null;
            ContentResolver cr = context.getContentResolver();
    
            Uri uri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
            String selection = MediaStore.Audio.Media.DATA;
            String[] selectionArgs = {path};
            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);
                    long id = Long.parseLong(cursor.getString(idIndex));
                    contentUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
                }
            }
            
            return contentUri;
    
        }
    

    Step 3

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

    finally, you can replace ‘MediaStore.Audio’ to ‘MediaStore.Video’

    I hope this helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search