Android中点击链接调起App

最近工作中的一个需求是点击短信链接则调起App然后完成相关功能逻辑,查阅相关文章完成需求,以此文章来记录Android中点击链接吊起App的实现。

原理

通过使用自定义Scheme方式,修改Scheme为自己的Scheme,来实现调起APP。
App通过注册intent filter声明intent,其它应用发送intent时通过系统级广播传递过来,如果与APP预先注册的intent filter匹配,App将收到该intent,实现调起App功能。

实现

自定义Scheme为:test://mytest.com/path?type=test
1.App的清单文件中添加intent-filter:

<activity
      android:name=".TestActivity">
      <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:host="mytest.com"
                android:pathPrefix="/path"
                android:scheme="test" />
      </intent-filter>
</activity>

2.在TestActivity.java的onNewIntent()/onCreate()方法中可以接收到相应的参数:

public void handleUri(Intent intent){
    String action = intent.getAction();
    Uri uri = intent.getData();
    if (uri != null) {
        String type= uri.getQueryParameter("type");
    }
}

其中相关API:

方法说明对应”test://mytest.com/path?type=test”的结果
getScheme()获取Uri中的scheme字符串部分test
getHost()获取Authority中的Host字符串mytest.com
getPath()获取Uri中path部分/path
getQuery()获取Uri中的query部分type=test
getQueryParameter(String key)获取Uri中query中key的值getQueryParameter(“type”)为test

这样就实现了点击链接调起App,根据相应参数进行处理完成相应需求。

注意:

1.在上述中的handleUri(Intent intent)方法中的intent对象:
(1)对于onCreate()方法通过this.getIntent()获取intent
(2)对于onNewIntent()方法则直接使用onNewIntent(Intent intent)中的intent。
在onNewIntent()方法中如果使用getIntent()获取intent对象会造成程序已经启动,点击链接地址调起App所获取到的Uri为Null。
2.关于getQueryParameter(String key)方法,如果Key中值带有”+”,使用此方获取到的值中会自动将”+”替换为空格,导致解密出错问题。
查阅相关资料,发现这是google api的bug。
网上有的说通过UrlQuerySanitizer.getParameterList()替代getQueryParameter方法,但亲测发现此方法得到的key的值会自动将”+”替换为”_”。
所以,无解,最终采取了最古老的截取字符串的方法。
如果大家有好的方法,欢迎讨论。
关于此问题参考文档:
https://blog.jamespan.me/2015/05/17/url-encoding
https://stackoverflow.com/questions/18281593/uri-getqueryparameter-not-working-with-and-symbols
参考文档:
http://blog.csdn.net/books1958/article/details/49948555
http://www.jianshu.com/p/58b9245a6f16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值