【问题标题】:I can't delete image from gallery with android我无法使用 android 从图库中删除图像
【发布时间】:2021-07-22 06:39:28
【问题描述】:

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

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

【问题讨论】:

  • 不要乱用 File 类。 MediaStore 有一个 .delete(uri) 成员。此外:不工作是一个糟糕的描述,因为我们不知道会发生什么。
  • Blackapps 你的意思是:MediaStore.createDeleteRequest(getContentResolver(), Collections.singleton(uri))?
  • 没有。没见过那个。不,getContentResolver().delete(uri)。
  • 我尝试了两个解决方案:1-getApplicationContext.getContentResolver().delete(uri,null,null) 2-getContentResolver().delete(uri,null) 但无法删除文件
  • 你得到了哪些错误。?然后你删除了一个uri。那个文件在哪里?我们不知道你在做什么。显示如何获取该 uri 的代码。然后显示删除代码。并告诉发生了什么。日志猫。例外。错误。

标签: java android image gallery


【解决方案1】:

我用这段代码解决了问题; 首先在 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;
}

并像这样从用户那里获取图像:get image from user

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2022-12-30
    相关资源
    最近更新 更多