android - 使用意图打开文件时如何修复内容无法显示的错误?
问题描述
我想以编程方式使用意图将文件显示给另一个应用程序,例如 pdf-viewer。但是没有应用程序可以解析文件内容并显示错误消息或立即关闭。我认为我的应用程序不会正确发送文件的内容,因此其他应用程序无法显示该文件。
我已经搜索了解决方案,但只找到了评论和帖子,问题在于打开文件。但这不是我的问题。
这是我的代码(不是我的,我从另一个网站得到的)打开文件:
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(filetype);
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri fileURI = FileProvider.getUriForFile(getContext(),
BuildConfig.APPLICATION_ID + ".fileprovider",file);
intent.setDataAndType(fileURI, mimeType);
} else {
intent.setDataAndType(Uri.fromFile(file), mimeType);
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
getContext().startActivity(intent);
}catch (ActivityNotFoundException e){
Toast.makeText(getContext(), "No Application found to open this type of file.", Toast.LENGTH_LONG).show();
}
String-var 'filetype' 是文件扩展名/类型,例如“pdf”或“txt”,获取正确的 mimetype 是没有问题的。文件对象“文件”是我的文件,我以这种方式创建:
File openFile = new File("MY_PATH");
也没有问题。
那么错误在哪里,或者有更好的代码,或者可以发布一个好的博客/堆栈溢出帖子的链接,或者与我的主题相关?提前谢谢你!
解决方案
我正在使用此代码共享图像,希望对您有所帮助:
private const val IMAGE_FORMAT = "image/jpg"
override fun shareFile(file: File) {
if (context != null) {
val contentUri = FileProvider.getUriForFile(context!!, FileManager.PROVIDER, file)
val intent = Intent(Intent.ACTION_SEND)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.type = IMAGE_FORMAT
intent.putExtra(Intent.EXTRA_STREAM, contentUri)
startActivity(Intent.createChooser(intent, getString(R.string.share_via)))
}
}
FileManager.PROVIDER
在您的情况下是提供者字符串BuildConfig.APPLICATION_ID + ".fileprovider"
推荐阅读
- kubernetes - 如何注入保险库并使用 hashcorp 保险库秘密?
- python - 从 csv 文件中的列分别读取字符串
- python - tkinter 选项菜单的虚拟事件
- javascript - 在js中声明和数组内部或外部forloop之间的区别
- laravel - Laravel 邮件 500
- python - 我收到名称错误。“instance_dict 未定义”
- java - 何时使用 Spring 的 CassandraTemplate 与 CassandraRepository
- javascript - Graphql-Query-Qenerator 如何创建布尔查询
- python - -1 和 1 之间的矩阵归一化
- android - 如何通过单击菜单项使 recyclerView 滚动到顶部位置?