我的android缓存系统有问题 我想要的是缓存我的最后一个视图为Android并在离线模式下打开它但在网上的情况下希望实时页面不是缓存的 如果我们把价格的任何网站作为这样的例子 http://www.oil-price.net/ 这是我的java类代码
public class Petroleum_price extends Fragment {
public Petroleum_price() {
// Required empty public constructor
}
Context context;
WebView mwebView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_petroleum_price, container, false);
context = container.getContext();
mwebView = new WebView(context);
mwebView = (WebView) v.findViewById(R.id.webView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mwebView.getSettings().setAppCachePath( getActivity().getApplicationContext().getCacheDir().getAbsolutePath() );
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.getSettings().setAllowFileAccess( true );
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSaveFormData(true);
CookieManager.getInstance().setAcceptCookie(true);
if ( !isNetworkAvailable() ) { // loading offline
mwebView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
mwebView.loadUrl( "http://www.oil-price.net/" );
return v;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
答案 0 :(得分:0)
您可以将此代码用于WebView
实施
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 );
webView.getSettings().setAppCachePath( 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( "http://www.google.com" );
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
并在清单中使用此代码
<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 load website when online, load local file when offline
的回答