从我的 Android 应用程序以编程方式打开选定的文件(图像、pdf 等)?

问题描述:

我正在开发一个 Android 应用程序,它应该能够打开特定文件夹中的选定文件.

I'm working on an Android application which should be able to open a selected file from a specific folder.

我已经试过了,但在选择了我想打开的应用程序后,我收到了这条消息:

I already tried this, but after selecting which application I want to open it, I got this message:

无法加载

在尝试了很多 线程 1 之后线程 2,我用这几行代码来做:

After trying a lot of thread 1 and thread 2, I use these lines of code to do it:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("/mnt/sdcard/xxx/xxx/Pictures/xxx.jpg"), "image/*");
myContext.startActivity(intent);

我该如何解决这个问题?

How can I figure this out?

试试下面的代码.我正在使用此代码打开 PDF 文件.您也可以将其用于其他文件.

Try the below code. I am using this code for opening a PDF file. You can use it for other files also.

File file = new File(Environment.getExternalStorageDirectory(),
                     "Report.pdf");
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
    startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {

}

如果要打开文件,可以更改setDataAndType(path, "application/pdf").如果你想以相同的意图打开不同的文件,你可以使用 Intent.createChooser(intent, "Open in...");.有关更多信息,请查看如何使用多个意图创建意图动作.

If you want to open files, you can change the setDataAndType(path, "application/pdf"). If you want to open different files with the same intent, you can use Intent.createChooser(intent, "Open in...");. For more information, look at How to make an intent with multiple actions.