標籤:
需求
通過手機瀏覽器直接開啟Android應用程式。假設本地已經安裝了指定Android應用,就直接開啟它;假設沒有安裝,則直接下載該應用的安裝檔案(也能夠跳轉到下載頁面)。
實現效果
假設手機上已經安裝了App。則直接開啟。假設沒有安裝,則開始下載。
實現方式
1.為Android應用的啟動Activity設定一個Schema,例如以下:
<data android:host="splash" android:scheme="huiyy" />
2.使用者點擊瀏覽器中的連結時,在動態建立一個不可見的iframe,而且讓這個iframe去載入步驟1中的Schema,例如以下:
/*scheme:必須*///scheme_IOS: ‘huiyy://‘,//scheme_Adr: ‘huiyy://splash‘,var ifr = document.createElement(‘iframe‘); ifr.src = ua.indexOf(‘os‘) > 0 ? config.scheme_IOS : config.scheme_Adr;
3,假設在指定的時間內沒有跳轉成功,則當前頁跳轉到apk的(或下載頁),例如以下:
window.location = download_url;
HTML代碼
<!doctype html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"/> <title>this‘s a demo</title> <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,minimal-ui"> </head> <body> <div> <a id="call-app" href="javascript:;" class="label">下載用戶端>></a> <input id="download-app" type="hidden" name="storeurl" value="http://www.baidu.com"> </div> <script> (function(){ var ua = navigator.userAgent.toLowerCase(); var t; var config = { /*scheme:必須*/ scheme_IOS: ‘huiyy://‘, scheme_Adr: ‘huiyy://splash‘, download_url: document.getElementById(‘download-app‘).value, timeout: 600 }; function openclient() { var startTime = Date.now(); var ifr = document.createElement(‘iframe‘); ifr.src = ua.indexOf(‘os‘) > 0 ? config.scheme_IOS : config.scheme_Adr; ifr.style.display = ‘none‘; document.body.appendChild(ifr); var t = setTimeout(function() { var endTime = Date.now(); if (!startTime || endTime - startTime < config.timeout + 200) { window.location = config.download_url; } else { } }, config.timeout); window.onblur = function() { clearTimeout(t); } } window.addEventListener("DOMContentLoaded", function(){ document.getElementById("call-app").addEventListener(‘click‘,openclient,false); }, false); })() </script> </body></html>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.downappdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.downappdemo.MainActivity" android:label="@string/app_name" > <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:host="splash" android:scheme="huiyy" /> </intent-filter> </activity> </application></manifest>
通過瀏覽器直接開啟Android應用程式