需求
通过手机浏览器直接打开Android应用程序。假设本地已经安装了指定Android应用,就直接打开它;假设没有安装,则直接下载该应用的安装文件(也能够跳转到下载页面)。
实现效果
假设手机上已经安装了App。则直接打开。假设没有安装,则開始下载。
实现方式
1.为Android应用的启动Activity设置一个Schema,例如以下:
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代码
this‘s a demo(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);
})()
AndroidManifest.xml
>
package="com.example.downappdemo"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="19" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.example.downappdemo.MainActivity"
android:label="@string/app_name" >