如何获得乌里从MediaStore通过文件的路径?如何获得、路径、文件、MediaStore

2023-09-05 09:41:37 作者:End丶已陌路

在我的计划,我要保存选定的铃声通过它的文件路径,然后将其设置为当前的铃声后。

In my program, I want to save a selected ringtone by it's file path, and then set it as the current ringtone later.

我已得到铃声preference铃声URI,并获得它的文件路径,从MediaStore数据库。

I have got the ringtone uri from RingtonePreference, and get the file path of it from MediaStore database.

例如。


Uri - content://media/internal/audio/media/29
Path - /system/media/audio/notifications/Ascend.mp3

现在,如何我从文件路径我得救了吗?得到的铃声乌里

Now, how to I get the ringtone Uri from the file path i saved ?

由于铃声在MediaStore已经存在,我想下面的功能,但它不工作。

Since the ringtone already exist in MediaStore, I tried the following functions, but it's not working.


uriRingtone = MediaStore.Audio.Media.getContentUriForPath(szRingtonePath);

URI是不一样的对视了一眼,我从铃声preference了。

The Uri is not the same as the one I got from RingtonePreference.


uriRingtone - content://media/internal/audio/media

我如何查询MediaStore得到乌里我需要什么?

How do I query the MediaStore to get the Uri I need?

P.S。我不存放铃声的Uri的直接原因是我发现的URI相同的铃声可能会在某些设备有时会改变。

p.s. the reason that I don't store the ringtone Uri directly is that I found the Uri for the same ringtone might change sometimes in some device.

推荐答案

您可以恢复存储在铃声preference铃声URI是这样的(据我所知)通过了解歌曲的标题。然后,你可以通过使用游标来获取铃声_id存储的查询,并用它,你可以建立一个URI:

The way you can recover the ringtone URI stored in the RingtonePreference is (as far as I know) by knowing the title of the song. Then you can query it by using a cursor to obtain the ringtone _id stored and with it you can build an URI:

String ringtoneTitle = "<The desired ringtone title>";
Uri parcialUri = Uri.parse("content://media/external/audio/media"); // also can be "content://media/internal/audio/media", depends on your needs
Uri finalSuccessfulUri;

RingtoneManager rm = new RingtoneManager(getApplicationContext()); 
Cursor cursor = rm.getCursor();
cursor.moveToFirst();

while(!cursor.isAfterLast()) {
    if(ringtoneTitle.compareToIgnoreCase(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE))) == 0) {
    int ringtoneID = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        finalSuccessfulUri = Uri.withAppendedPath(parcialUri, "" + ringtoneID );
        break;
    }
    cursor.moveToNext();
}

在这里finalSuccessful URI是URI指向的铃声preference铃声。

where finalSuccessful uri is the uri pointing to the ringtone in the RingtonePreference.