您的位置:首页 > 移动开发 > Android开发

浏览器通过JS打开Android程序

2016-04-26 00:00 127 查看
摘要: JS打开Android

做项目的时候,项目中有个需求,需要通过网页打开app,听到这个功能,我先是蛋疼了一会,但是在网上查了一下资料发现原理其实很简单,本质就是通过浏览器输入我们本地android程序的路径,不过这个路径需要我们在android中AndroidManifest.xml声明一下

<activity android:name=".LoadingActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

<intent-filter>//配置可以通过浏览器启动Intent
<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="zhu" /> //自己定义的协议
</intent-filter>

</activity>


这个地方配置了后,我们可以试到在浏览器上输入zhu://splash


这会自动的跳转到搜索页面,这是因为浏览器如果发现地址的前缀不是http等常见的协议就会自动跳到搜索的页面,某些还会在前面自动加上http。

既然这样没办法,那我就直接写了个js代码来实现这跳转

window.location = "zhu://splash";


访问js页面



项目的需求之后又变了一下,不仅要打开我们的App还要判断当没有App的时候自动下载它

代码如下:

<script>
(function(){
var t;
function openclient() { //判断在规定时间内是否可以打开app,如果超时就代码没有安装对应的app 跳到下载页面。

var startTime = Date.now();

window.location = "zhu://splash";
var t = setTimeout(function() {
var endTime = Date.now();
if (endTime - startTime < 800) {
window.location = “你的下载地址”;
}
}, 600);

window.onblur = function() {
clearTimeout(t);
}
}
window.addEventListener("DOMContentLoaded", function(){ //添加监听事件
openclient();
}, false);
})()
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js android