从assets或res/raw中获取文件的Uri

3
我尝试过许多不同的在线资源(正如您可以从我所做的所有评论中看到的),以使其工作。我想要访问位于assets或res中的.pdf文件;无论哪个位置都可以,只要最简单的方式即可。
我有下面的方法,将获取实际文件并使用参数中的Uri调用另一个方法(在下面第一个方法之下)。
非常感谢您的帮助,我将随时待命回答问题或添加更多内容。
private void showDocument(File file)
{
    //////////// ORIGINAL ////////////////////
    //showDocument(Uri.fromFile(file));
    //////////////////////////////////////////

    // try 1
    //File file = new File("file:///android_asset/RELATIVEPATH");

    // try 2
    //Resources resources = this.getResources();

    // try 4
    String PLACEHOLDER= "file:///android_asset/example.pdf";
    File f = new File(PLACEHOLDER);

    //File f = new File("android.resource://res/raw/slides1/example.pdf");

    //getResources().openRawResource(R.raw.example);

    // try 3
    //Resources resources = this.getResources();
    //showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));

    showDocument(Uri.fromFile(f));
}

protected abstract void showDocument(Uri uri);
3个回答

8

来自链接获取存储在Android res / raw文件夹中的.mp3文件的URI

使用资源ID时,格式如下:

"android.resource://[package]/[res id]"

Uri路径 = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);

或者,使用资源子目录(类型)和资源名称(没有扩展名的文件名),格式如下:

"android.resource://[包]/[资源类型]/[资源名称]"

Uri路径 = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");


2
非常有帮助的文章。
以下是另一种方法:在可能的情况下,使用文件描述符而不是Uri。
例如:(在我的情况下,这是一个原始音频文件)
FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();

this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);

2
如果您不知道资源的ID,只知道名称,可以使用Android Resouces对象getIdentifier(...)方法。您可以使用应用程序上下文的getResources()来检索后者。
例如,如果您的资源存储在/res/raw文件夹中:
String rawFileName = "example"  // your file name (e.g. "example.pdf") without the extension

//Retrieve the resource ID:
int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());

if ( resID == 0 ) {  // the resource file does NOT exist!!
    //Debug:
    Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");

    return;
}

//Read the resource:
InputStream inputStream = context.getResources().openRawResource(resID);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接