无法删除SD卡的一首歌

问题描述 投票:0回答:4

我想创建代码,使我的音乐应用程序从存储中删除歌曲。到目前为止,是成功地删除该文件,如果该文件是在内部(仿真)存储(即不应用程序的内部存储空间,但手机的内部共享存储)。但是,只要歌声是外置SD卡上,该file.delete()不删除该文件并返回false。

这是我到目前为止的代码:

//Remove selected tracks from the database 
activity.getContentResolver()
     .delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, selection.toString(), null);

//Delete File from storage
File file = new File(song.getFilePath);
if(!file.delete()){
   Log.e("MusicFunctions", "Failed to delete file: " + song.getFilePath());
}

当我选择一首歌曲是在SD卡中,并没有被删除,而只是被从数据库中删除;这里是一个logcat的输出:

E/MusicFunctions: Failed to delete file: /storage/3138-3763/Music/Test/Odesza/In Return/Always This Late.mp3

我也曾尝试context.deleteFile(file)但我也没有运气。

正如我所说的,它不但不能删除文件的时候就在SD卡上。当它被保存在内部存储,它会删除罚款。为什么它不会删除,什么是删除从Android 5.0以上版本的SD卡上的文件的正确方法?

提前谢谢了。

编辑:我忘了提,我已经添加的权限:

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

而我得到在运行时所需的存储权限:

ActivityCompat.requestPermissions(thisActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL);

第二个编辑:我注意到,文件管理器应用程序需要被授予的其他权限,下面就像在https://metactrl.com/docs/sdcard-on-lollipop/步骤

我怎样才能做到这一点?

android file android-sdcard
4个回答
2
投票

我注意到,该问题再次有了一些兴趣。我很高兴地说,我确实找到了一个解决问题的办法。我做了广泛的网上调查,发现了一些源代码文件(虽然我很抱歉,我不记得在那里我发现他们),它解决了我的问题

与Android 4.4以上版本的问题是,你需要通过存储访问架构额外的特权,以便第三方应用删除/修改外部SD卡的文件。

为了得到这些特权,你需要获取文档的URI或其父文件(目录)URI之一。要做到这一点,你需要打开Android的内置文件浏览器。最好是它的用户通过文件浏览器选择了SD卡根目录,使您的应用程序可以修改/删除SD卡上的任何文件。要做到这一点,你可以按照下面的代码:

private int REQUEST_CODE = 42;
private void getSDCardAccess(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == RESULT_OK) {
        Uri treeUri = resultData.getData();
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);

        getContentResolver().takePersistableUriPermission(treeUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION |
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        if(shrdPref == null){
            shrdPref = getSharedPreferences(PREF_MAIN_FILE, MODE_PRIVATE);
        }
        //Takes the access so that we can use it again after the app reopens
        shrdPref.edit().putString(KEY_SDCARDSTORAGE, treeUri.toString()).apply();
    }
}

另外你需要一个文件的“文档文件”,以修改和删除文件。下面的代码片段可以帮助你做到这一点,以及检测,如果一个文件/目录中的文档文件的方法是可写的......(我知道它的很多代码,其中大部分来自于另一个来源。我真后悔忘记在那里我得到了它,因为他们做应该有一个很大的功劳)。你会愿意知道的功能是:isWritableNormalOrSAF(),DELETEFILE()和可能的CopyFile()。请注意,大多数的其它功能都需要这些工作)

public static boolean isWritable(@NonNull final File file) {
    boolean isExisting = file.exists();

    try {
        FileOutputStream output = new FileOutputStream(file, true);
        try {
            output.close();
        }
        catch (IOException e) {
            // do nothing.
        }
    }
    catch (FileNotFoundException e) {
        return false;
    }
    boolean result = file.canWrite();

    // Ensure that file is not created during this process.
    if (!isExisting) {
        // noinspection ResultOfMethodCallIgnored
        file.delete();
    }

    return result;
}


public static boolean isWritableNormalOrSaf(@Nullable final File folder, Context context) {
    // Verify that this is a directory.
    Log.e("StorageHelper", "start");
    if (folder == null || !folder.exists() || !folder.isDirectory()) {
        Log.e("StorageHelper", "return 1");
        return false;
    }

    // Find a non-existing file in this directory.
    int i = 0;
    File file;
    do {
        String fileName = "AugendiagnoseDummyFile" + (++i);
        file = new File(folder, fileName);
        //Log.e("StorageHelper", "file:" + fileName);
    }
    while (file.exists());

    // First check regular writability
    if (isWritable(file)) {
        //Log.e("StorageHelper", "return 2 true");
        return true;
    }

    // Next check SAF writability.
    Log.e("StorageHelper", "start 2");
    DocumentFile document;
    try {
        document = getDocumentFile(file, false, false, context);
    }
    catch (Exception e) {
        //Log.e("StorageHelper", "return 3 exception");
        return false;
    }

    if (document == null) {
        //Log.e("StorageHelper", "return 4 doc null");
        return false;
    }

    // This should have created the file - otherwise something is wrong with access URL.
    boolean result = document.canWrite() && file.exists();

    // Ensure that the dummy file is not remaining.
    document.delete();

    //Log.e("StorageHelper", "return end");
    return result;
}


public static boolean deleteFile(@NonNull final File file, Context context) {
    // First try the normal deletion.
    if (file.delete()) {
        return true;
    }

    // Try with Storage Access Framework.
        DocumentFile document = getDocumentFile(file, false, true, context);
        return document != null && document.delete();

}




private static DocumentFile getDocumentFile(@NonNull final File file, final boolean isDirectory, final boolean createDirectories, Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_MAIN_FILE, Context.MODE_PRIVATE);
    String uriString = sharedPreferences.getString(KEY_SDCARDSTORAGE, null);
    if(uriString == null){
        return null;
    }

    Uri treeUri = Uri.parse(uriString);

    String fullPath;
    try {
        fullPath = file.getCanonicalPath();
    }
    catch (IOException e) {
        return null;
    }

    String baseFolder = null;

    // First try to get the base folder via unofficial StorageVolume API from the URIs.
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        StorageVolume volume = storageManager.getStorageVolume(file);
        String uuid = volume.getUuid();

        String volumeId = getVolumeIdFromTreeUri(treeUri);
        if (uuid.equals(volumeId)) {
            // Use parcel to get the hidden path field from StorageVolume
            Parcel parcel = Parcel.obtain();
            volume.writeToParcel(parcel, 0);
            parcel.setDataPosition(0);
            parcel.readString();
            parcel.readInt();
            String volumeBasePath = parcel.readString();
            parcel.recycle();
            baseFolder = getFullPathFromTreeUri(treeUri, volumeBasePath);
        }

    }
    else {
        // Use Java Reflection to access hidden methods from StorageVolume
        String treeBase = getFullPathFromTreeUri(treeUri, getVolumePath(getVolumeIdFromTreeUri(treeUri), context));
        if (treeBase != null && fullPath.startsWith(treeBase)) {
            treeUri = treeUri;
            baseFolder = treeBase;
        }
    }




    if (baseFolder == null) {
        // Alternatively, take root folder from device and assume that base URI works.
        baseFolder = getExtSdCardFolder(file, context);
    }

    if (baseFolder == null) {
        return null;
    }

    String relativePath = fullPath.substring(baseFolder.length() + 1);

    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);

    String[] parts = relativePath.split("\\/");
    for (int i = 0; i < parts.length; i++) {
        DocumentFile nextDocument = document.findFile(parts[i]);

        if (nextDocument == null) {
            if (i < parts.length - 1) {
                if (createDirectories) {
                    nextDocument = document.createDirectory(parts[i]);
                }
                else {
                    return null;
                }
            }
            else if (isDirectory) {
                nextDocument = document.createDirectory(parts[i]);
            }
            else {
                nextDocument = document.createFile("image", parts[i]);
            }
        }
        document = nextDocument;
    }

    return document;
}









@Nullable
private static String getFullPathFromTreeUri(@Nullable final Uri treeUri, final String volumeBasePath) {
    if (treeUri == null) {
        return null;
    }
    if (volumeBasePath == null) {
        return File.separator;
    }
    String volumePath = volumeBasePath;
    if (volumePath.endsWith(File.separator)) {
        volumePath = volumePath.substring(0, volumePath.length() - 1);
    }

    String documentPath = getDocumentPathFromTreeUri(treeUri);
    if (documentPath.endsWith(File.separator)) {
        documentPath = documentPath.substring(0, documentPath.length() - 1);
    }

    if (documentPath.length() > 0) {
        if (documentPath.startsWith(File.separator)) {
            return volumePath + documentPath;
        }
        else {
            return volumePath + File.separator + documentPath;
        }
    }
    else {
        return volumePath;
    }
}


private static String getVolumeIdFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    final String[] split = docId.split(":");

    if (split.length > 0) {
        return split[0];
    }
    else {
        return null;
    }
}

private static final String PRIMARY_VOLUME_NAME = "primary";
private static String getVolumePath(final String volumeId, Context context) {
    try {
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

        Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

        Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
        Method getUuid = storageVolumeClazz.getMethod("getUuid");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
        Object result = getVolumeList.invoke(storageManager);

        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String uuid = (String) getUuid.invoke(storageVolumeElement);
            Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);

            // primary volume?
            if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                return (String) getPath.invoke(storageVolumeElement);
            }

            // other volumes?
            if (uuid != null) {
                if (uuid.equals(volumeId)) {
                    return (String) getPath.invoke(storageVolumeElement);
                }
            }
        }

        // not found.
        return null;
    }
    catch (Exception ex) {
        return null;
    }
}


private static String getDocumentPathFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    final String[] split = docId.split(":");
    if ((split.length >= 2) && (split[1] != null)) {
        return split[1];
    }
    else {
        return File.separator;
    }
}


public static String getExtSdCardFolder(@NonNull final File file, Context context) {
    String[] extSdPaths = getExtSdCardPaths(context);
    try {
        for (String extSdPath : extSdPaths) {
            if (file.getCanonicalPath().startsWith(extSdPath)) {
                return extSdPath;
            }
        }
    }
    catch (IOException e) {
        return null;
    }
    return null;
}

private static String[] getExtSdCardPaths(Context context) {
    List<String> paths = new ArrayList<>();
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0) {
                Log.w("StorageHelper", "Unexpected external file dir: " + file.getAbsolutePath());
            }
            else {
                String path = file.getAbsolutePath().substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                }
                catch (IOException e) {
                    // Keep non-canonical path.
                }
                paths.add(path);
            }
        }
    }
    return paths.toArray(new String[paths.size()]);
}








public static boolean copyFile(@NonNull final File source, @NonNull final File target, Context context) {
    FileInputStream inStream = null;
    OutputStream outStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {
        inStream = new FileInputStream(source);

        // First try the normal way
        if (isWritable(target)) {
            // standard way
            outStream = new FileOutputStream(target);
            inChannel = inStream.getChannel();
            outChannel = ((FileOutputStream) outStream).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        }
        else {
            // Storage Access Framework
            DocumentFile targetDocument = getDocumentFile(target, false, true, context);
            if (targetDocument != null) {
                outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
            }

            if (outStream != null) {
                // Both for SAF and for Kitkat, write to output stream.
                byte[] buffer = new byte[4096]; // MAGIC_NUMBER
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            }

        }
    }
    catch (Exception e) {
        Log.e("StorageHelper",
                "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e);
        return false;
    }
    finally {
        try {
            inStream.close();
        }
        catch (Exception e) {
            // ignore exception
        }
        try {
            outStream.close();
        }
        catch (Exception e) {
            Log.e("StorageHelper", "OutStreamClose: " + e.toString());
            // ignore exception
        }
        try {
            ((FileChannel) inChannel).close();
        }
        catch (Exception e) {
            // ignore exception
        }
        try {
            outChannel.close();
        }
        catch (Exception e) {
            Log.e("StorageHelper", "OutChannelClose: " + e.toString());
            // ignore exception
        }
    }
    return true;
}


    public static String getExtensionFromName(String fileName){
    String extension = "";

    int i = fileName.lastIndexOf('.');
    if (i > 0) {
        extension = fileName.substring(i+1);
    }

    return extension;
}

0
投票

试试这个

File file = new File(song.getFilePath);
  if(!file.delete()){
   if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
        getApplicationContext().deleteFile(file.getName());
     }
    }
  }

0
投票

您可以尝试使用规范的文件删除方法

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}

0
投票

你的文件的路径是错误的,你应该从ContentProvider的通过URI,如何通过URI来获取绝对路径查询绝对路径检查这个问题,How to get the Full file path from URI

© www.soinside.com 2019 - 2024. All rights reserved.