[英]Android - How do I open a file in another app via Intent?
我正在嘗試使用其他應用程序打開文件,即打開帶有Gallery的.jpg,帶有Acrobat的.pdf等。
我遇到的問題是,當我嘗試在應用程序中打開文件時,它只打開所選應用程序而不是在應用程序中打開文件。 我嘗試通過Intent跟隨Android打開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類型:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg
在此處發布我的更改,以防它可以幫助其他人。 我最終將下載位置更改為內部文件夾並添加了內容提供程序。
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 6及以下版本上工作得很好,沒有在更高版本上測試過
public void openFile(final String fileName){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
.getAbsolutePath()+ File.separator+"/Folder/"+fileName));
intent.setDataAndType(uri, "audio/mpeg");
startActivity(intent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.