First store your website's file in asset folder.
Now everytime you open the app, check if the website file exists or not to prevent app from crashing.
The code given below checks that and if it doesn't exist, then it calls a method which copies the file from asset to device storage.
File file = new File(YOUR FILE PATH);
if(!file.exists()){
//Doesn't exist. Create it in sdcard
copyAssets();
}
Here are the methods to copy the website file from asset to device storage (put them in your class) -
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(DIRECTORY, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Then check internet connection of user (in oncreate method) -
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//user is connected to internet
//put the code given ahead over here
}
Permission -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now if the user is connected to the internet, access the internet and get your website's new source code like this (put this code in internet checking code given above) -
URL url = new URL(YOUR URL);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
String source = a.toString();
Now once you have the source code, update your HTML file in device storage like this -
File gpxfile = new File(File address, "filename.html");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(source); //our new source code
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
You are done! Now load your file to webView from storage like this (in oncreate method after all the code that we wrote before) -
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+ "Your address in storage");
It is recommended to send user requests time to time to turn on their internet to update the website and prevent use of outdated copy of it.