can't delete file from external storage in android programmatically

前端 未结 4 692
面向向阳花
面向向阳花 2020-12-16 15:11

I am trying to delete a file located at the path

/storage/714D-160A/Xender/image/Screenshot_commando.png

What I\'ve done so far:

         


        
4条回答
  •  心在旅途
    2020-12-16 15:45

    From Android 4.4 onwards, you can't write to SD card files (except in the App directory) using the normal way. You'll have to use the Storage Access Framework using DocumentFile for that.

    The following code works for me:

    private void deletefile(Uri uri, String filename) {
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri);
        try {
            getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    
        DocumentFile file = pickedDir.findFile(filename);
        if(file.delete())
            Log.d("Log ID", "Delete successful");
        else
            Log.d("Log ID", "Delete unsuccessful");
    }
    

    where filename is the name of the file to be deleted and uri is the URI returned by ACTION_OPEN_DOCUMENT_TREE:

    private static final int LOCATION_REQUEST = 1;
    
    private void choosePath() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        startActivityForResult(intent, LOCATION_REQUEST);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == LOCATION_REQUEST && resultCode == Activity.RESULT_OK) {
            Uri uri;
            if (resultData != null) {
                uri = resultData.getData();
                if (uri != null) {
                    try {
                        getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
    
                    /* Got the path uri */
                }
            }
        }
    }
    

提交回复
热议问题