我无法使用 android 从图库中删除图片

I can't delete image from gallery with android

我在 android 中有一个项目,我想从图库中 select 多个图像,然后删除文件或重命名文件。但是他们两个都不工作,我不知道为什么!

public void fileRename(Uri uri){
//File file=new File(uri.getPath());
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
        filePathColumn, null, null, null);
cursor.moveToFirst();
File file=new File(cursor.getString(cursor.getColumnIndex(filePathColumn[0])));
if(file.exists()){
    boolean del=file.delete();
    if(del){
        Toast.makeText(this, "Trueee", Toast.LENGTH_SHORT).show();
    }
}

我用这段代码解决了问题; 先在Manifest中添加这个权限:

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

和 API 29 将此添加到应用程序标签:

android:requestLegacyExternalStorage="true"

下一步获得用户的许可:

if(!checkPermission()){
        requestPermission();
    }

和功能:

    private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        try {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
            startActivityForResult(intent, 2296);
        } catch (Exception e) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            startActivityForResult(intent, 2296);
        }
    } else {
        //below android 11
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, 10);
    }
}


private boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        return Environment.isExternalStorageManager();
    } else {
        int result = 0;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            result = context.checkSelfPermission(READ_EXTERNAL_STORAGE);
            int result1 = context.checkSelfPermission(WRITE_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
        }
        }
    return true;
}

并像这样从用户那里获取图像:

然后使用以下代码从存储中删除:

    public void fileDelete(Uri uri){

    final String docId;
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;

        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        String selection = "_id=?";
        String[] selectionArgs = new String[]{split[1]};


        String temp=getDataColumn(context, contentUri, selection,
                selectionArgs);
        File file=new File(temp);
        if(file.exists()){
            if(file.delete()){
                Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(context, "not Deleted", Toast.LENGTH_SHORT).show();
            }
        }

    }else if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        File file=new File(cursor.getString(cursor.getColumnIndex(filePathColumn[0])));
        if(file.exists()){
            if(file.delete()){
                Toast.makeText(this, "deleted", Toast.LENGTH_SHORT).show();
                if(file.exists()){
                    Toast.makeText(this, "Exist", Toast.LENGTH_SHORT).show();
                }
            }
            else Toast.makeText(this, "Not Exist", Toast.LENGTH_SHORT).show();
        }
    }}


private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};

    try {
        cursor = context.getContentResolver().query(uri, projection,
                selection, selectionArgs, null);

        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    }
    finally {
        if (cursor != null)
            cursor.close();
    }

    return null;
}

要刷新图库,请使用此代码:

    MainActivity.this.sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE",Uri.fromFile(file)));