Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 中監聽 PhoneGap WebView 的載入事件

編輯:關於 Android 程式設計

先前寫過一篇關於攔截 PhoneGap WebView 事件的方法:在實作 CordovaInterface 的 Activity 中,於 onMessage 裡依第一個參數的 message name 判斷 WebView 的載入狀態。

但這個做法在 Fragment 場景下會失效。若同一個 Activity 內掛載了多個含 WebView 的 Fragment,onMessage 就無法分辨事件究竟來自哪一個 WebView。

經過嘗試後發現,仍然可以用 setWebViewClient() 的方式解決:覆寫 WebViewClient 的 onPageStarted、onPageFinished、onReceivedError 等回呼,各自處理對應的載入階段。因為每個 WebView 各自持有自己的 client 物件,事件來源自然不會混淆。

CordovaWebView webView = (CordovaWebView) findViewById(R.id.webView);

CordovaInterface cordovaInterface = (CordovaInterface) context;

CordovaWebViewClient cordovaWebViewClient = new CordovaWebViewClient(cordovaInterface, webView) {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        LogUtil.debug("onPageStarted " + url);
        super.onPageStarted(view, url, favicon);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        LogUtil.debug("onPageFinished " + url);
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        LogUtil.debug("onReceivedError " + failingUrl);
        super.onReceivedError(view, errorCode, description, failingUrl);
        progressBar.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
    }
};

webView.setWebViewClient(cordovaWebViewClient);
webView.loadUrl(url);

幾個實作細節

記得呼叫 super:每個覆寫方法都應先呼叫父類別的實作。CordovaWebViewClient 內除了頁面導航,還負責 bridge 與外掛的初始化等作業,漏掉的話容易出現難以定位的異常。

每個 Fragment 各自建立 client:關鍵在於 client 是綁定到個別 WebView 的。把這段程式寫在 Fragment 自己的 onCreateView() 之後,每個 Fragment 就會擁有獨立的 progressBar 與 errorView 狀態。

載入失敗的處理:onReceivedError 中把載入進度條收掉並顯示錯誤畫面,是較完整的做法;此處 also 建議改用 failingUrl 而非 url 記錄,因為前者才是真正載入失敗的位址。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved