且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 android 浏览器启动自定义 android 应用程序

更新时间:2022-12-21 10:28:21

使用 带有 元素.例如,要处理到 twitter.com 的所有链接,您可以将其放在 中的 AndroidManifest.xml 中:

<intent-filter>
    <data android:scheme="http" android:host="twitter.com"/>
    <action android:name="android.intent.action.VIEW" />
</intent-filter>

然后,当用户在浏览器中点击 Twitter 链接时,他们会被询问使用什么应用程序来完成操作:浏览器还是您的应用程序.

Then, when the user clicks on a link to twitter in the browser, they will be asked what application to use in order to complete the action: the browser or your application.

当然,如果您想在您的网站和应用之间提供紧密的集成,您可以定义自己的方案:

Of course, if you want to provide tight integration between your website and your app, you can define your own scheme:

<intent-filter>
    <data android:scheme="my.special.scheme" />
    <action android:name="android.intent.action.VIEW" />
</intent-filter>

然后,在您的网络应用程序中,您可以放置​​如下链接:

Then, in your web app you can put links like:

<a href="my.special.scheme://other/parameters/here">

当用户点击它时,您的应用程序将自动启动(因为它可能是唯一可以处理 my.special.scheme:// 类型的 uris 的应用程序).唯一的缺点是如果用户没有安装该应用程序,他们会收到一个令人讨厌的错误.而且我不确定有什么方法可以检查.

And when the user clicks it, your app will be launched automatically (because it will probably be the only one that can handle my.special.scheme:// type of uris). The only downside to this is that if the user doesn't have the app installed, they'll get a nasty error. And I'm not sure there's any way to check.

要回答您的问题,您可以使用 getIntent().getData() 返回一个 Uri 对象.然后您可以使用 Uri.* 方法来提取您需要的数据.例如,假设用户点击了一个指向 http://twitter.com/status/1234 的链接:

To answer your question, you can use getIntent().getData() which returns a Uri object. You can then use Uri.* methods to extract the data you need. For example, let's say the user clicked on a link to http://twitter.com/status/1234:

Uri data = getIntent().getData();
String scheme = data.getScheme(); // "http"
String host = data.getHost(); // "twitter.com"
List<String> params = data.getPathSegments();
String first = params.get(0); // "status"
String second = params.get(1); // "1234"

您可以在 Activity 的任何位置执行上述操作,但您可能希望在 onCreate() 中执行此操作.您还可以使用 params.size() 来获取 Uri 中的路径段数.查看 javadoc 或 android 开发者网站,了解可用于提取特定部分的其他 Uri 方法.

You can do the above anywhere in your Activity, but you're probably going to want to do it in onCreate(). You can also use params.size() to get the number of path segments in the Uri. Look to javadoc or the android developer website for other Uri methods you can use to extract specific parts.