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

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

问题描述

我其实刚接触Java编程,但我一直在以下几个解决方案,我的问题就在这里,但没有找到一个适合我的情况,我似乎不能正确地下来拿到code。

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.

我想有它打开一个在线的页面(例如谷歌)一个web视图的时候,手机在线,并打开一个本地的HTML页面的时候,手机处于离线状态。

i would like to have a WebView which 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 how this could be done? some simple pointing to the right direction could help.

非常感谢

推荐答案

这听起来像一个简单的web视图缓存机制给我。

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();
}

最后,不要忘了以下三个权限添加到您的的Andr​​oidManifest.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天全站免登陆