Reputation: 4659
I use webview to load html pages and urls.
I want to load url only if internet is available or if the url content is cached by the web view.
How can I check if a url is cached without having to create my own cache on some external path.
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wv.setOnTouchListener(this);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.contains("http")) {
view.loadUrl(url);
} else {
if (Utils.isConnectingToInternet(thisActivity)) {
view.loadUrl(url);
}
}
view.loadUrl(url);
return false;
}
I have referred to :
Check if file already exists in webview cache android
How to move webView cache to SD?
Android webview check if page is in cache
Upvotes: 12
Views: 4679
Reputation: 2810
Working version of @vidha 's answer without using deprecated API and in Kotlin:
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
if (request.url.toString() == view.url) {
// showInternetConnectionError()
webView.loadUrl("file:///android_asset/error_state.html")
}
super.onReceivedError(view, request, error)
}
Upvotes: 0
Reputation: 1345
Try overriding onPageCommitVisible
inside your webviewclient
. When the URL is not cached and the network is not available, this callback will be called.
@Override
public void onPageCommitVisible(WebView view, String url) {
super.onPageCommitVisible(view, url);
if(!isNetworkAvailable){
//page not cached
}
Timber.d("Page cannot draw")
}
Check internet availability
boolean isNetworkAvailable(){
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Upvotes: 0
Reputation: 1277
Set webview cache mode LOAD_CACHE_ELSE_NETWORK.
Override WebViewClient methods :
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.getUrl().equals(failingUrl)){
showInternetConnectionError();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
It will load webpage from server if internet connection available, otherwise load from cache. If webpage is not available in cache then it will display internet connection error.
Upvotes: 1