android中使用URL Scheme方式启动app

URL Scheme作为android中拉起app的一种方式,还是比较常见的

好处

  • 可以从网页中拉起app
  • 可以拉起具体Activity

说明

android通过url scheme打开activity,只需要在manifest 中配置以下几个参数即可

<manifest>
    <application>
        <activity>
            <intent-filter>
                <data
                    android:host="***"
                    android:path="***"
                    android:scheme="***">
                </data>
                ...

实际上<data> 中还有其他参数,若有复杂的需求可以研究下。

这里看下这几个参数就可以了,可以参考url格式

android:scheme 协议类型
android:host 主机地址
android:path 具体路径

android:scheme="http"
android:host="www.baidu.com"
android:path="/s"

http://www.baidu.com/s?wd=what

这样的链接在浏览器中也可以直接访问的

举个例子

在activity中加入
<intent-filter>
    <data
        android:host="www.adc.com"
        android:path="/person"
        android:scheme="myapp"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>

这样通过链接 myapp://www.abc.com/person 就可以打开此activity了;
可以再复杂些,比如打开activity打开某个用户的信息 myapp://www.abc.com/person?id=123

从html网页中启动app

让另一个app显示其中的人员信息,那只要传入一个id就可以了
在html中,直接使用url链接启动app,并且可以打开具体的activity

<a href="myapp://www.abc.com/person?id=123&search=https://www.baidu.com/s?wd=what">start app</a>

从java代码中启动app

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("myapp://www.abc.com/person?id=123&search=https://www.baidu.com/s?wd=what"));
startActivity(intent);

解析传入的参数

Intent intent = getIntent();
String action = intent.getAction();
if(Intent.ACTION_VIEW.equals(action)){
   Uri uri = intent.getData();
   if(uri != null){
      String id = uri.getQueryParameter("id"); // id="123"
      String search = uri.getQueryParameter("search"); // search="https://www.baidu.com/s?wd=what"
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章