浏览器经过JS打开Android程序

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

<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。 app

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

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


     访问js页面 code

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

    代码以下: 事件

<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>
相关文章
相关标签/搜索