0

使用 webview,以下代码将在网上正常执行,并将显示 PDF 文件。之后,如果我离线,它将不会显示缓存的 pdf 文件。

mWebview.getSettings().setJavaScriptEnabled(true);
String pdfStr="https://www.sample.structure.first.pdf";
mWebview.loadUrl("https://docs.google.com/gview?embedded=true&url=" + pdfStr);

但我需要缓存 pdf 并在离线模式下显示它。有人对此有任何想法吗?

4

1 回答 1

1

You can save your work in cache of Web view using following:

WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 );
webView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );

if ( !isNetworkAvailable() ) { 
    webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}

webView.loadUrl( "your_url" );

Add this method to check if network is available:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Add these permissions in your manifest :

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
于 2016-04-26T09:07:25.227 回答