簡體   English   中英

將Webview內容保存到android存儲並加載

[英]Save webview content to android storage and load it

我想制作一個具有webview布局的android應用程序。 這是我的申請標准:

  1. 該應用程序第一次啟動時,Webview會加載一個URL(也許是Facebook,Google等)。webview.loadUrl(“ http://www.google.com”);

  2. 加載網址后,應用程序會將加載的網址保存到android內部存儲器中“特定位置”的HTML視圖(file.htm)中。 因此,假設我打開“ google.com”,該應用程序將Google的網頁保存為HTML文件(例如,文件名“ google.htm”),然后當我轉到該“特定位置”並單擊“ google .htm”文件,它將使用android的HTML查看器顯示Google網頁。

  3. 當應用程序再次啟動時,或者只是說應用程序再次加載了url(在本例中為“ google.com”)時,它不會從“ google.com”頁面中獲取,但會從“ google.htm”中獲取文件在內部存儲的android上。 因此,從用戶的角度來看,即使未連接到Internet,該應用程序仍可以加載網頁。

簡單起見

  1. 應用程序開始->轉到指定的URL->檢查存儲
  2. 如果存在指定的URL,則存儲中有HTML文件,然后從存儲中加載
  3. 否則,它將從Web加載URL。

誰能幫我提供代碼和解釋? 我真的很感激。 謝謝大家:D

您可以在WebView使用Javascript接口,以在頁面加載完成后返回HTML源代碼的全部。 為此,您需要將自己的WebViewClient分配給WebView。

為此,請在Activity類中使用類似於以下內容的內容- 確保您的Activity實現了Observer

public void onCreate(Bundle savedInstanceState) {
    // ...

    webView.setWebViewClient(new MyWebViewClient());
    HtmlJSInterface htmlJSInterface = new HtmlJSInterface();
    webView.addJavascriptInterface(htmlJSInterface, "HTMLOUT");
    htmlJSInterface.addObserver(this);

    // ...
}

// Called when our JavaScript Interface Observables are updated.
@Override
public void update(Observable observable, Object observation) {

    // Got full page source.
    if (observable instanceof HtmlJSInterface) {
        html = (String) observation;
        onHtmlChanged();
    }
}

private void onHtmlChanged() {
    // Do stuff here...
}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // When each page is finished we're going to inject our custom
        // JavaScript which allows us to
        // communicate to the JS Interfaces. Responsible for sending full
        // HTML over to the
        // HtmlJSInterface...
        isStarted = false;
        isLoaded = true;
        timeoutTimer.cancel();
        view.loadUrl("javascript:(function() { "
                + "window.HTMLOUT.setHtml('<html>'+"
                + "document.getElementsByTagName('html')[0].innerHTML+'</html>');})();");
        }
    }
}

然后,您將要創建HtmlJSInterface類,如下所示:

   public class HtmlJSInterface extends Observable {
  private String html;

  /**
   * @return The most recent HTML received by the interface
   */
  public String getHtml() {
    return this.html;
  }

  /**
   * Sets most recent HTML and notifies observers.
   * 
   * @param html
   *          The full HTML of a page
   */
  public void setHtml(String html) {
    this.html = html;
    setChanged();
    notifyObservers(html);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM