簡體   English   中英

使用從MediaStore.Audio.Media.DATA中提取的uri刪除文件

[英]Delete file using uri extracted from MediaStore.Audio.Media.DATA

在將此問題標記為重復之前,我想說我曾訪問過許多類似的問題,但沒有一個解決了我的問題。因此,我已經使用MediaStore從內部存儲中提取了所有音頻文件,並將其Uri以字符串形式存儲,但是稍后我嘗試時要使用file.delete使用該Uri刪除音頻,前者返回false。 以下是提取歌曲uri及其正常工作的代碼:

    Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection=MediaStore.Audio.Media.IS_MUSIC+"!=0";
    Cursor c=getContentResolver().query(uri,null,selection,null,null);
    if(c!=null)
    {
        c.moveToFirst();

        do {
            String audioName=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
            String artist=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String album=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String url=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
            String size=c.getString(c.getColumnIndex(MediaStore.Audio.Media.SIZE));

            audioInfoArrayList.add(new AudioInfo(url,audioName,artist,album));

        }while (c.moveToNext());

        c.close();

在這里,我已將所有與音頻有關的信息存儲在自定義類型的arrayList中,該信息還以字符串形式存儲了上面提取的uri,可以使用getUrl()方法進行提取。 以下是我如何嘗試刪除代碼的代碼:

Uri uri= Uri.parse(audioInfo.get(position).getUrl()); //its actually returning the url stored above in string form
deleteFile(uri.getPath());
Log.i("logText","uri.getPath() : "+uri.getPath());
Log.i("logText","audioInfo.get(position).getUrl() : "+audioInfo.get(position).getUrl());

deleteFile函數:

public void deleteFile(String filePath){
    if(filePath.startsWith("content://")){
        ContentResolver contentResolver = context.getContentResolver();
        contentResolver.delete(Uri.parse(filePath), null, null);
    }else {
        File file = new File(filePath);
        if(file.exists()) {
            if (file.delete()) {
                Log.e("logText", "File deleted."); //condition 0
            }else {
                Log.e("logText", "Failed to delete file!");  //condition 1
            }
        }else {
            Log.e("logText", "File not exist!"); //condition 2
        }
    }
} 

最后是我的logcat,用於示例音頻文件:

 01-11 13:52:34.257 19982-19982/com.example.hp.myplayer E/logText: Failed to delete file! 01-11 13:52:34.257 19982-19982/com.example.hp.myplayer I/logText: uri.getPath() : /storage/emulated/0/bluetooth/Copy Copy Fireflies-Owl_City[www.Mp3MaD.Com].mp3 01-11 13:52:34.257 19982-19982/com.example.hp.myplayer I/logText: audioInfo.get(position).getUrl() : /storage/emulated/0/bluetooth/Copy Copy Fireflies-Owl_City[www.Mp3MaD.Com].mp3 

注意:在調用deleteFile()時,條件1不會執行2或0,這對我來說意味着文件是使用該uri在存儲中定位的,但無法刪除,並且file.delete()返回false。

對於Android 6及更高版本,僅在清單中請求讀取和寫入外部存儲許可是不夠的。

您應該添加代碼以要求您的應用程序用戶確認請求的權限。

Google的運行時權限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM