WebView 在线时加载网站,离线时加载本地文件 [英] WebView load website when online, load local file when offline

查看:21
本文介绍了WebView 在线时加载网站,离线时加载本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是 Java 编程的新手,但我在这里一直在遵循多种解决方案来解决我的问题,但没有找到适合我的情况,而且我似乎无法正确获取代码.

I am actually new to programming in Java but I have been following several solutions to my problem here but didn't find one that suits my case and I can't seem to get the code down correctly.

我想要一个 WebView,它可以在手机在线时打开一个在线页面(例如 Google),并在手机离线时打开一个本地 HTML 页面.

I would like to have a WebView that opens an online page (for example Google) when the phone is online and open a local HTML page when the phone is offline.

同时,虽然我希望手机在线时覆盖本地页面,以便离线本地页面始终更新到手机上次连接到互联网的时间.

At the same time though I want the phone to overwrite the local page when it is online so that the offline local page is always updated to the last time the phone was connected to the internet.

关于如何做到这一点的任何想法?一些简单的指向正确的方向可能会有所帮助.

Any ideas on how this could be done? Some simple pointing to the right direction could help.

非常感谢.

推荐答案

对我来说,这听起来像是一个简单的 webview 缓存机制.

That sounds like a simple webview caching mechanism to me.

以下内容应该符合您的要求:

The following should do what you are looking for:

WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
webView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default

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

webView.loadUrl( "http://www.google.com" );

方法 isNetworkAvailable() 检查活动的网络连接:

The method isNetworkAvailable() checks for an active network connection:

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

最后别忘了在你的AndroidManifest.xml中添加以下三个权限:

Finally, don't forget to add the following three permissions to your AndroidManifest.xml:

<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"/>

这篇关于WebView 在线时加载网站,离线时加载本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆