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"
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章