我正在尝试使用其他应用程序打开文件,例如使用画廊打开.jpg,使用Acrobat打开.pdf等。
我的问题是当我尝试在应用程序中打开文件时,它只会打开所选的应用程序,而不是在应用程序内打开文件。我尝试遵循Android通过Intent打开pdf文件,但我可能错过了一些步骤。
public String get_mime_type(String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = null;
if (ext != null) {
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
return mime;
}
public void open_file(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), filename);
// Get URI and MIME type of file
Uri uri = Uri.fromFile(file).normalizeScheme();
String mime = get_mime_type(uri.toString());
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(mime);
context.startActivity(Intent.createChooser(intent, "Open file with"));
}
据我所知,它返回了正确的URI和MIME类型:
As far as I can tell, it returns the right URI and MIME type:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg
setData()
之后调用setType()
会清除数据,所以最好使用setDataAndType()
。 - Lukas