利用URL Scheme打開APP並傳遞數據

利用外部鏈接打開APP並傳遞一些附帶信息是現在很多APP都有的功能,我在這把這部分的知識記錄一下。

1、什麼是URL Scheme?

android中的scheme是一種頁面內跳轉協議,是一種非常好的機制,通過自己在AndroidManifest.xml文件裏面定義自己的scheme協議,可以非常方便的跳轉到App的各個頁面。通過scheme協議,甚至可以跳轉到App的某個頁面,可以通過直接輸入URL進行跳轉,也可以把URL寫進HTML頁面進行跳轉。

2、實現的大致流程

我們手機的APP可以向操作系統註冊一個URL Scheme,該scheme用於從瀏覽器或其他應用中啓動本應用。

3、URL Scheme的協議格式

tlqp://my.app/openwith?roomID=123456

scheme:tlqp 代表Scheme的協議名稱(必須)

host:my.app 代表host

path:openwith 代表path

query:roomID=123456 代表URL傳遞的值

4、設置URL Scheme

<intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
            
<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:scheme="tlqp" android:host="my.app" android:pathPrefix="/openwith" />    
</intent-filter>
在AndroidManifest.xml文件,添加以上代碼(根據情況適當修改),這裏需要注意的地方是,不能再上面的Intent-filter裏面添加相關代碼,因爲那裏面存在MAIN和LAUNCHER相關代碼,混在一起的話,會造成App圖標丟失的情況。需要新建一個intent-filter,然後把代碼添加進去即可。


5、獲取URL附帶的參數

Uri uri = getIntent().getData();
if (uri != null) {
    // 完整的url信息
    String url = uri.toString();
    Log.e(TAG, "url: " + uri);
    // scheme部分
    String scheme = uri.getScheme();
    Log.e(TAG, "scheme: " + scheme);
    // host部分
    String host = uri.getHost();
    Log.e(TAG, "host: " + host);
    //port部分
    int port = uri.getPort();
    Log.e(TAG, "host: " + port);
    // 訪問路勁
    String path = uri.getPath();
    Log.e(TAG, "path: " + path);
    List<String> pathSegments = uri.getPathSegments();
    // Query部分
    String query = uri.getQuery();
    Log.e(TAG, "query: " + query);
    //獲取指定參數值
    String goodsId = uri.getQueryParameter("goodsId");
    Log.e(TAG, "goodsId: " + goodsId);
}


6、打開app的方式

可以把URL寫進HTML裏面通過點擊網頁鏈接打開APP

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
        <title>Insert title here</title>

    </head>

    <body>

        <a href="tlqp://my.app/openwith?roomID=203518">打開app</a><br/>

    </body>

</html>

原生調用方式:

  Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("xl://goods:8888/goodsDetail?goodsId=10011002"));
  startActivity(intent);

後記:目前有一部分瀏覽器是打不開App的,例如;qq瀏覽器,UC瀏覽器這些,百度瀏覽器也有可能打不開,原因是這些瀏覽器都在你的Scheme前面加上了http://,從而造成了scheme失效。還有一點需要注意,就是上面說到的url裏面的path這個參數,如果你的path包含了其他的path,那麼你調用這個包含其他path的path,可能會在打開第一個path對應的頁面的同時也會打開被包含path的那個頁面,有點繞口麼~舉個栗子吧

<a href="tlqp://my.app/hello?roomID=123456">打開hello</a> 吊起hello,沒問題
<a href="tlqp://my.app/helloworld?roomID=123456">打開helloworld</a> 這個會弔起hello和helloworld。



發佈了137 篇原創文章 · 獲贊 36 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章