注册为自定义文件类型的默认应用程序
注册才能打开自定义类型的文件。假设我有 .cool 文件,如果用户尝试打开它,Android 会询问他们是否愿意使用我的应用程序打开它。如何?
Register to be able to open files of custom type. Say i have .cool files, and if the user tries to open it, Android asks if they would like to open it with my application. How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将以下内容添加到必须打开文件(在本例中为 pdf)的 Activity 内的 AndroidManifest.xml 文件中。
确保指定正确的 mime 格式。如果用户想要打开“pdf”文件,系统将提示她选择您的应用程序。
另请检查 Android 意图过滤器:将应用与文件扩展名相关联更多细节。
You can add the following to the AndroidManifest.xml file inside the activity that has to open the file (pdf in our case)
Make sure you specify the proper mime format. The user will be prompted to choose your app if she wants to open the "pdf" file.
Check also Android intent filter: associate app with file extension for more details.
我认为你不会选择那个。这是由系统处理的。当您发送要由地图处理的意图时也是如此,例如,如果您有 Skyfire,系统会弹出一个窗口,您可以选择应用程序并选择是否希望它始终打开此类文件。
当然,除非您的应用程序是唯一打开此类文件的应用程序。
编辑
我认为如果您希望您的应用程序说“嘿,我能够打开这些 .cool 文件”,您需要使用标签
设置
并指定 mimeType 或 Uri。 查看此处了解更多详细信息。
;I think that you don't choose that. This is handle by the system. Same thing when you send an intent to be handled by a map, If you have skyfire for instance, the system pops up a window an you can choose the application and choose if you want it to always open this kind of file.
Unless of course if your application is the only one to open this kind of file.
Edit
I think if you want your app to say "hey I'm able to open these .cool files", you need to set up
<intent-filters>
with a tag<data>
and specificy the mimeType or Uri. Check here for more details.这是一个更完整的示例,展示如何注册您的应用程序以打开纯文本文件。
注册您可以处理的文件类型
将
intent-filter
添加到清单中的活动中。在我的例子中,ReaderActivity
将显示文本文件。mimeType
表示我将接受任何纯文本文件。有关特定文件扩展名,请参阅此。处理 Intent
从 Activity 中的 Intent 获取数据,如下所示:
您可以使用
getData()
从 Intent 获取数据,以获取文件的 URI。然后,您使用内容解析器打开输入流。您使用内容解析器是因为您可能无法直接访问该文件。感谢这个答案提供了将输入流转换为字符串的方法。Here is a fuller example to show how to register your app to open plain text files.
Register the type of file you can handle
Add an
intent-filter
to your activity in the manifest. In my case it is theReaderActivity
that will display the text file. ThemimeType
says that I will accept any plain text file. See this for specific file extensions.Handle the intent
Get the data from the intent in your activity like this:
You get the data from the intent with
getData()
to get the URI to the file. Then you use the content resolver to open an input stream. You use the content resolver because you might not have direct access to the file otherwise. Thanks to this answer for the method to convert the input stream to a string.显示了一种可能的答案
此处
。在您的活动标签之一中使用它,当按下文件时它将被打开。我使用 Oreo 中的原生 Android 文件管理器对其进行了测试。
One possible answer is shown
here
. Use this inside one of your activity tag and it'll be opened when the file have been pressed. I tested it using the native android file manager in Oreo.