如何在 Android 上实现我自己的 URI 方案 [英] How to implement my very own URI scheme on Android

查看:36
本文介绍了如何在 Android 上实现我自己的 URI 方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想定义一个 URI,例如:

myapp://path/to/what/i/want?d=This%20is%20a%20test

必须由我自己的应用程序或服务处理.请注意,方案是 "myapp" 而不是 "http""ftp".这正是我的意图:为 Android 操作系统全局定义我自己的 URI 模式.这可能吗?

这有点类似于一些已经在 Windows 系统上执行的程序,例如 Skype (skype://) 或任何 torrent 下载程序 (torrent://).

解决方案

这很有可能;您在 AndroidManifest.xml 中定义 URI 方案,使用 <data> 元素.您设置了一个填充了 元素的 Intent 过滤器,然后您就可以创建自己的方案了.(更多关于这里的意图过滤器和意图解析.)>

这是一个简短的例子:

<意图过滤器><action android:name="android.intent.action.VIEW"/><category android:name="android.intent.category.DEFAULT"/><category android:name="android.intent.category.BROWSABLE"/><data android:scheme="myapp" android:host="path"/></意图过滤器></活动>

根据隐式意图的工作原理,您还需要至少定义一个操作和一个类别;在这里,我选择 VIEW 作为动作(尽管它可以是任何东西),并确保添加 DEFAULT 类别(因为这是所有隐式意图所必需的).还要注意我是如何添加 BROWSABLE 类别的 - 这不是必需的,但它可以让您的 URI 从浏览器中打开(一个漂亮的功能).

Say I want to define that an URI such as:

myapp://path/to/what/i/want?d=This%20is%20a%20test

must be handled by my own application, or service. Notice that the scheme is "myapp" and not "http", or "ftp". That is precisely what I intend: to define my own URI schema globally for the Android OS. Is this possible?

This is somewhat analogous to what some programs already do on, e.g., Windows systems, such as Skype (skype://) or any torrent downloader program (torrent://).

解决方案

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

这篇关于如何在 Android 上实现我自己的 URI 方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆