Android-如何通过Intent在另一个应用程序中打开文件? [英] Android - How do I open a file in another app via Intent?
问题描述
我正在尝试使用其他应用打开文件,即使用Gallery打开.jpg,使用Acrobat打开.pdf等.
I'm trying to open a file using another app, i.e. opening a .jpg with Gallery, .pdf with Acrobat, etc.
我遇到的问题是,当我尝试在应用程序中打开文件时,它只会打开所选的应用程序,而不是在应用程序中打开文件.我尝试按照通过Intent进行Android打开pdf文件的操作,但我一定会丢失一些东西.
The problem I'm having with this is when I try to open the file in the app, it only opens the chosen app instead of opening the file within the app. I tried following Android open pdf file via Intent but I must be missing something.
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
推荐答案
在此处发布我的更改,以防它可以帮助其他人.我最终将下载位置更改为一个内部文件夹,并添加了内容提供程序.
Posting my changes here in case it can help someone else. I ended up changing the download location to an internal folder and adding a content provider.
public void open_file(String filename) {
File path = new File(getFilesDir(), "dl");
File file = new File(path, filename);
// Get URI and MIME type of file
Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
String mime = getContentResolver().getType(uri);
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mime);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
这篇关于Android-如何通过Intent在另一个应用程序中打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!