如何从ACTION_OPEN_DOCUMENT返回的URI中获取完整的绝对路径?

时间:2019-05-24 10:36:16

标签: java android uri

@Anonymous's answer对于获取树URI(ACTION_OPEN_DOCUMENT_TREE)的完整绝对路径非常有用。

类似地,我想获取从ACTION_OPEN_DOCUMENT返回的URI的完整绝对路径。

public void selectSong(View view) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("audio/*");

    try {
        startActivityForResult(intent, Constants.FILE_REQUEST);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(this, "Failed to open the system file picker dialog; Are you sure you're runing Android Kitkat or up?", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == Constants.FILE_REQUEST && resultCode == Activity.RESULT_OK) {
        if (resultData != null) {
            Uri uri = resultData.getData();

            if (uri != null) {
                try {
                    getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } catch (SecurityException e) {
                    e.printStackTrace();
                }

                /* I'd like to get the full absolute path of `uri` */
                //String path = getFullPathFromDocumentUri(uri);
            }
        }
    }
}

我尝试过

uri.getPath(); //Returns: /document/FAEC-4302:Musics♪/Song.mp3
uri.toString(); //Returns: content://com.android.externalstorage.documents/document/FAEC-4302%3AMusics%E2%99%AA%2FSong.mp3

// `FAEC-4302` is my external SD card
// The selected file Song.mp3 is in the Musics♪ folder in the SD Card

我想获得类似/storage/FAEC-4302/Musics♪/Song.mp3

的输出

我想获得完整的绝对路径的原因是

  1. 我要使用的库要求歌曲文件有一个FILE对象,并且我需要完整的绝对路径来创建一个FILE对象。
  2. 我想实现一种功能,将文件保存在与歌曲相同的位置,并且我需要歌曲的完整绝对路径才能做到这一点

如何从ACTION_OPEN_DOCUMENT返回的URI中获取完整的绝对路径?

0 个答案:

没有答案