看啥推荐读物
专栏名称: 所謂向日葵族
目录
相关文章推荐
今天看啥  ›  专栏  ›  所謂向日葵族

Android 自定义scheme及多端唤起使用方法

所謂向日葵族  · 掘金  ·  · 2019-10-08 12:18
阅读 16

Android 自定义scheme及多端唤起使用方法

前言

DeepLink,深度链接技术,类似于web开发领域不仅仅是通过链接打开一个界面,而是打开界面的某个具体内容。常用于web端唤起app时,传递参数直接打开确定的界面,如通过京东的分享出去的商品详情页,实现在京东app中打开。

在移动开发领域,是指app在处理特定的url时能够直接跳转到对应的内容页面或者触发特定的逻辑。这样可以在web端切换app时通过参数传递保留了当前的上下文状态,又可以借用web端的优势,更利于传播,可利用搜索引擎的索引,增加app的日活和下载量等。

移动端实现deeplink于是就有了Universal Link、App Link、URL schemes等

Android配置scheme

如配置WebActivity完整的打开链接为openapp://test:8000/detail,需要在AndroidManifest.xml配置

<activity android:name=".WebActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <!--需要被js调起必须设置-->
        <category android:name="android.intent.category.BROWSABLE" />
        <!--协议部分-->
        <data
            android:host="test"
            android:path="/detail"
            android:port="8000"
            android:scheme="openapp" />
    </intent-filter>
</activity>
复制代码

协议部分:(类比于http://locahost:8080/home)

  • android:scheme:协议名,类似于http
  • android:host:主机名,类似于locahost
  • android:port:端口名。类似于8080中的端口
  • android:path:路径名,类似于home
  • 还可以配置imei等等。结构为<scheme>://<host>:<port>/[<path>|<pathPrefix>|<pathPattern>]

Android端调起

通过指定Intent的Action为Intent.ACTION_VIEW,传入解析的Uri

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("openapp://test:8000/detail?title=电视影音&url=https://u.jd.com/1dfFwO"));
startActivity(intent);
复制代码

传递参数的方法跟web端一样,通过问号?分隔,参数名和值之间使用等号=连接,多个参数之间使用&拼接。

Android端参数接收

Uri uri = getIntent().getData();
if (uri != null) {
    // 完整的url信息
    String totalUrl = uri.toString();
    Log.i(TAG, "完整url: " + totalUrl);
    // scheme 协议
    String scheme = uri.getScheme();
    Log.i(TAG, "scheme: " + scheme);
    // host 主机
    String host = uri.getHost();
    Log.i(TAG, "host: " + host);
    //port 端口
    int port = uri.getPort();
    Log.i(TAG, "port: " + port);
    // 访问路径
    String path = uri.getPath();
    Log.i(TAG, "path: " + path);
    // 获取所有参数
    String query = uri.getQuery();
    Log.i(TAG, "query: " + query);
    //获取指定参数值
    String title = uri.getQueryParameter("title");
    Log.i(TAG, "title: " + title);
    String url = uri.getQueryParameter("url");
    Log.i(TAG, "url: " + url);
}
复制代码

唤起后可以看见打印的日志信息: {% asset_img 15705317238763.png%}

拿到参数之后就可以进行后续的使用操作啦

web端唤起

直接当做一个普通的连接形式,直接跳转

window.location = "openapp://test:8000/detail?title=电视影音&url=https://u.jd.com/1dfFwO";  
复制代码

或者设置超链接等待用户点击

<a href="openapp://test:8000/detail?title=电视影音&url=https://u.jd.com/1dfFwO">在app中打开</a>
复制代码

原文链接

💡 更多好文欢迎关注我的公众号~

公众号




原文地址:访问原文地址
快照地址: 访问文章快照