The files related to a package are stored under
/data/user/0/PACKAGENAME/ (absolute path) /data/data/PACKAGENAME/ (canonical path)
getFilesDir() or getCacheDir() in Activity file can be used to get these paths
try {
Log.i("Files dir Abs path" , getCacheDir().getAbsolutePath());
//data/user/0/com.aravindsankaran.webarchieveandsystemdirs/files/
Log.i("Files dir Canonical" , getFilesDir().getCanonicalPath());
//data/data/com.aravindsankaran.webarchieveandsystemdirs/files
Log.i("Cache dir" , getCacheDir().getCanonicalPath());
//data/data/com.aravindsankaran.webarchieveandsystemdirs/cache
Log.i("External Cache dir" , getExternalCacheDir().getCanonicalPath());
//storage/emulated/0/Android/data/com.aravindsankaran.webarchieveandsystemdirs/cache
} catch (Exception e) {
e.printStackTrace();
}
When a web page is saved as an archieve, it saves the images, scripts and other files locally as .mht file.
Command used to save: webView.saveWebArchieve(PATHTOSAVE)
Command used to load : webView.loadUrl("file://" + PATHTOARCHIEVE)
WebView webView = (WebView) findViewById(R.id.webView);
final File archieve = new File(getFilesDir(),"archieve.mht");
Log.i("archive",archieve.getAbsolutePath());
//data/user/0/com.aravindsankaran.webarchieveandsystemdirs/files/archieve.mht
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
//save archive after the webpage is loaded. Otherwise, we get empty page
if(!archieve.exists()){
view.saveWebArchive(archieve.getAbsolutePath());
Log.i("saved","page saved");
}
super.onPageFinished(view, url);
}
});
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
To check internet connection, we need the following permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission>
To load from archieve when not connected to internet
//load page if connected to internet or restore from archieve if available
if(isConnected())
webView.loadUrl("http://www.google.com");
else{
if(archieve.exists())
webView.loadUrl("file://" + archieve.getAbsolutePath());
else
webView.loadData("<h1>No Connection</h1>","text/html","UTF-8");
}
}
boolean isConnected(){
ConnectivityManager cm =
(ConnectivityManager)getApplicationContext().
getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean connection = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return connection;
}