1. 程式人生 > >在html頁面中判斷本地app是否安裝並開啟

在html頁面中判斷本地app是否安裝並開啟

html中其實是無法判斷應用是否安裝,除非在webview中通過js bridge,這裡通過一種方式達到此目的。

1、編輯AndroidManifest.xml:

    主要是增加第二個<intent-filter>,myapp用來標識schema,最好能保證手機系統唯一,那樣就可以開啟應用,而不是彈出一個選擇框。

    android:pathPrefix標識url的path,可以附帶自己的資料通過string傳遞到activity,比如完整url為 myapp://xxx/openwith?data=mydata

          <activity
            android:name="com.abc.MainActivity"
            android:configChanges="orientation|keyboardHidden|navigation|screenSize"
            android:screenOrientation="landscape"
            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>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="myapp" android:pathPrefix="/xxx/openwith" />
            </intent-filter>
        </activity>
   然後通過activity獲得data資料:
    public void onCreate(Bundle savedInstanceState) {
        Uri uridata = this.getIntent().getData();
        String mydata = uridata.getQueryParameter("data");
        ...
   }

  2、編寫html頁面:

   整個頁面也許是某個app的詳細介紹,這裡只寫出關鍵的js程式碼:

   function openApp() {

           if (/android/i.test(navigator.userAgent)) {
                var isrefresh = getUrlParam('refresh'); // 獲得refresh引數
                if(isrefresh == 1) {
                    return
                }
                window.location.href = 'myapp://xxx/openwith?data=mydata';
                window.setTimeout(function () {
                        window.location.href += '&refresh=1' // 附加一個特殊引數,用來標識這次重新整理不要再呼叫myapp:// 了
                }, 500);
            }

   }
  上面程式碼可以達到這樣一個目的,先請求 myapp:// ,如果系統能處理,或者說已經安裝了myapp表示的應用,那麼就可以開啟,另外,如果不能開啟,直接重新整理一下當前頁面,等於是重置location。