1. 程式人生 > >webapp檢測安卓app是否安裝並launch

webapp檢測安卓app是否安裝並launch

nbsp rdo agen bsp 後臺 方法 ins 動態 dev

1. cordova插件

1)查看所有已安裝的安卓app

https://www.npmjs.com/package/cordova-plugin-packagemanager

A simple plugin that will return a list of installed applications or all on your smartphone. Retuen uid, dataDir and packageName.

function successCallback(e) {
    alert(JSON.stringify(e));
}

function errorCallback(e) {
    alert(
‘Error!‘ + e); } window.plugins.packagemanager.show(true, successCallback, errorCallback);

2)檢測某安卓app是否已安裝

https://www.npmjs.com/package/cordova-plugin-appavailability

從1)返回的list of installed applications中找到所需app的scheme,例如高德地圖:com.autonavi.minimap。

var scheme;

if (device.platform === ‘iOS‘) {
    scheme 
= ‘iosamap://‘; } else if (device.platform === ‘Android‘) { scheme = ‘com.autonavi.minimap‘; } appAvailability.check( scheme, // URI Scheme or Package Name function () { // Success callback alert(scheme + ‘ is available :)‘); }, function () { // Error callback
alert(scheme + ‘ is not available :(‘); } );

3)launch app

https://github.com/nchutchind/cordova-plugin-app-launcher

window.plugins.launcher.launch(
                { uri: ‘androidamap://route?sourceApplication=cortanademoservice&slat=39.979366&slon=116.31028&sname=我的位置&dlat=39.980016&dlon=116.326568&dname=公安局&dev=0&t=0‘ },
                successCallback,
                errorCallback
            );

2. JavaScript的tricky實現方法

安裝app的情況下,網頁會進入後臺打開app,網頁進入後臺後會掛起js的執行,但是這個期間有600-1000ms的時間js仍然會執行,可以利用打開app的延時來判斷是否有該app。

var t = 1000, hasApp = true;
setTimeout(function () {
    if (!hasApp) {
        cordova.InAppBrowser.open(‘http://m.amap.com/navigation/carmap/saddr=116.310322%2C39.978957%2C%E5%BE%AE%E8%BD%AF%E5%A4%A7%E5%8E%A6&daddr=116.326568%2C39.980016%2C%E4%B8%AD%E5%85%B3%E6%9D%91%E6%B4%BE%E5%87%BA%E6%89%80&saddr_lonlat=116.310322%2C39.978957%2C%E5%BE%AE%E8%BD%AF%E5%A4%A7%E5%8E%A6&daddr_lonlat=116.326568%2C39.980016%2C%E4%B8%AD%E5%85%B3%E6%9D%91%E6%B4%BE%E5%87%BA%E6%89%80&saddr_typecode=120201&daddr_typecode=130501&saddr_poiid=B0FFFSPTNE&daddr_poiid=B000A7FCSP&maddr=&sort=&addPassing=remove‘);
    }
    $("#ifr").remove();
}, 2000);

var t1 = Date.now();
var ifr = $(‘<iframe id="ifr"></iframe>‘)
ifr.attr(‘src‘, ‘androidamap://route?sourceApplication=cortanademoservice&slat=39.979366&slon=116.31028&sname=我的位置&dlat=39.980016&dlon=116.326568&dname=公安局&dev=0&t=0‘);
$(‘body‘).append(ifr);
setTimeout(function () {
    var t2 = Date.now();
    //delay time 30 may vary for different type of phones
    if (!t1 || t2 - t1 < t + 30) {
        hasApp = false;
    }
}, t);

利用iframe的動態加載來嘗試打開app。

webapp檢測安卓app是否安裝並launch