通過瀏覽器直接開啟Android App 應用程式
阿新 • • 發佈:2019-02-17
點選瀏覽器中的URL連結,啟動特定的App。
首先做成HTML的頁面,頁面內容格式如下:
<a href="[scheme]://[host]/[path]?[query]">啟動應用程式</a>
這一句就可以了。
當然上面的 在標準形式,對於正常情況而言是OK的,但是每個瀏覽器有自己的特定義設定。
各個專案含義如下所示:
scheme:判別啟動的App。 ※詳細後述
host:適當記述
path:傳值時必須的key ※沒有也可以
query:獲取值的Key和Value ※沒有也可以
作為測試如下:
<a href="myapp://jp.app/openwith?name=zhangsan&age=26">啟動應用程式</a>
首先在AndroidManifest.xml的MAIN Activity下追加以下內容。(啟動Activity時給予)
<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="myapp" android:host="jp.app" android:pathPrefix="/openwith"/> </intent-filter>
HTML記述的內容加入<data …/>。
其中必須的內容僅scheme,沒有其他內容app也能啟動。
※注意事項:intent-filter的內容【android.intent.action.MAIN】和 【android.intent.category.LAUNCHER】這2個,不能與這次追加的內容混合。
所以,如果加入了同一個Activity,請按以下這樣做,否則會導致應用圖示在桌面消失等問題。
<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="myapp" android:host="jp.app" android:pathPrefix="/openwith"/> </intent-filter>
接下來在Activity中需要取值的地方新增以下程式碼,我是直接寫在OnCreate函式裡的:
Intent i_getvalue = getIntent();
String action = i_getvalue.getAction();
if(Intent.ACTION_VIEW.equals(action)){
Uri uri = i_getvalue.getData();
if(uri != null){
String name = uri.getQueryParameter("name");
String age= uri.getQueryParameter("age");
}
}
首先,是UC瀏覽器,如果你使用了自己的scheme,而不是http的話,uc會預設在你的scheme前面新增http://。這太坑爹了。其他瀏覽器沒看是不是同樣的情況。發現這個問題後我就試著把自己的scheme換成http。然後滿懷期待的又跑了一遍,結果還是坑爹了。所以我想會不會是第三方瀏覽器對url做了處理。到這裡,我也無可奈何了。我測試了UC,獵豹,歐朋,這3個都不支援。系統自帶的和谷歌瀏覽器是支援的,但是最新版的谷歌瀏覽器好像也不支援了,firefox目前還支援。
官方的文件有解釋:http://developer.android.com/guide/topics/manifest/data-element.html
scheme://host:port/path or pathPrefix or pathPattern
這裡面定義的schema+host+port+(path or pathPrefix or pathPattern)能拼湊出一個http連結,包含這個filter的Activity,能處理這個http連結。
執行結果應該是,有安裝該應用的話,會開啟該應用,如果沒有會跳轉到指向的頁面。在HTML頁面裡面可以自動重定向到下載連結,這個就能自動下載。