This article is fromhttp://blog.csdn.net/chenshaoyang0011
In the previous note http://www.voidcn.com/article/p-tghalzgl-em.html, the solution is describedXMLXML span>Carry inCDATAandHTMLThe solution to physical characters, the next problem to be solved is to cache pictures.
This article mainly records the solutions to the following problems :
1,< /span>Response to the picture click event in WebView
2,WebView Picture cache, andReplace the default WebView picture (that is, the style displayed before the picture is loaded)
In the news content When displaying, pictures are indispensable. After the content is loaded, the caching of pictures is also very necessary. After all, for mobile applications, traffic is a very precious resource. For pictures, WebView itself has a cache database for caching. But what I use is another idea for image caching-to prevent WebView from loading the image, but after the WebView loads the text, download the image through the local method and save it locally before displaying it in the WebView. In this way, it can be more flexible when using WebView for display.
Before implementing the functions mentioned above, you need to understand How does Android’s WebView implement mutual calls between Java code and JavaScript code? Two blog posts are recommended http://blog.csdn.net/wangtingshuai/article/details/8631835 (implementation of simple calls) and http://www.voidcn.com /article/p-tvdfmyhz-nm.html (Implement image click) This article will not repeat it. Next, we will discuss the implementation methods of the above functions in detail.
一, Respond to the picture click event in WebView.
For the realization of this function, please refer to http ://www.voidcn.com/article/p-tvdfmyhz-nm.html This article. Which mainly involves the intermodulation of JS and JAVA code, here I will not reinvent the wheel.
Two , Cache the picture in the WebView, replace the default picture
WebView itself has its own caching mechanism, but because I didn’t find the relevant documents, it didn’t feel very useful, so I thought of another method. The main idea is as follows: 1. Use jsoup to parse html; 2. Get the URLs of all pictures (that is, the url of the img tag), replace them with the URIs of the pictures that need to display the default state, and finally follow these URIs after the pictures are downloaded Replace a certain mapping rule with a local URI (that is, point the img to a local picture); 3. Close the WebView to load the picture and load the html; 4. After the text is loaded, start to download all the imgs to Locally, after each picture is downloaded, call the js code to refresh the picture.
The following is a step by step implementation.
1 Use jsoup to parse html
This I am at http: //www.voidcn.com/article/p-uzbecwwk-em.html has been briefly introduced, and for detailed usage, please refer to http://jsoup.org/ (the code in the following uses many jsoup apis).
2 Get the urls of all pictures and replace them with local pictures (need to replace the pictures with the default display effect of WebView).
The url of the obtained picture needs to be saved in an attribute List
-
public List
imgUrls = new ArrayList();
Use the following code snippets to get the URLs of all img tags from html, and follow the mapping rules below Replace with the URI of the local picture (Of course, this mapping rule is up to you~~): “http://…/xx.xx” is replaced with “file://mnt/sdcard/test/xx.xx” is actually the path where the image is saved after downloading.
-
Document doc = null; /span>
-
ImgUrls.clear();
-
Elements es = doc.getElementsByTag(“img”);
li>
-
-
for (Element e: es) {< /span>
-
String imgUrl = e.attr(“src”);
-
imgUrls.add(imgUrl);
-
File file = new File(imgUrl );
-
imgName = file.getName();
-
if(imgName.endsWith(“.gif”)){
-
e.remove();
-
}else{ < /span>
-
-
String filePath = “file:///mnt/sdcard/test/ “ + imgName;
-
e.attr(“src”,“file:///android_asset/web_logo.png”);
-
e.attr(“src_link”, filePath);
-
e.attr(“ori_link”,imgUrl);
-
String str = “window.” + Js2JavaInterfaceName + “.setImgSrc(‘”
-
+ filePath + “‘)”;
< /li>
-
e.attr(“onclick”, str);
-
-
< li>
String imgName;
< br style="font-family:arial;font-size:14px;line-height:2 6px;background-color:#ffffff;">
3, close WebView to load network pictures, load html and display first Text content
This is mainly to improve the user experience. Preventing WebView from loading images by itself is to avoid repetitive downloading of images to avoid wasting traffic.
First, close the WebView to load the network image. In fact, since we have replaced the url in the img, this step can be ignored. But in order to avoid fish that slip through the net, it is better to add:
webView.getSettings().setBlockNetworkImage(true);
Next load html:
< /p>
-
//result is the html text obtained after parsing span>
-
webView.loadDataWithBaseURL(null , result, “text/html”, “utf-8”, null); span>
4. After the text is loaded After that, start to download all imgs to the local in turn. After each picture is downloaded, call the js code to refresh the picture.
After the text content is loaded, you can start to load the image content. After the html content is loaded After that, the method WebViewClient.onPageFinished(WebView view, String url) will be called. We can download and save the image in this method.
The following code snippet realizes the function of downloading:
-
webView.setWebViewClient(new WebViewClient(){
-
-
publicvoid onPageFinished(WebView view, String url){
-
//DownloadWebImgTask is a class for downloading pictures
-
DownloadWebImgTask downloadTask = new DownloadWebImgTask();
-
-
//Get the url of all pictures
-
List
urlStrs = parser.getImgUrls (); -
-
String urlStrArray[] = new String[urlStrs.size() + 1];
-
urlStrs.toArray(urlStrArray);
-
-
//Start downloading
-
downloadTask.execute(urlStrArray);
-
-
-
-
});
The implementation of DownloadWebImgTask in the above code is as follows, its function is to download pictures in batches, and refresh the WebView after each picture is downloaded. Since WebView itself does not provide an interface to realize the separate refresh of the picture (at least I did not find it…), this function can only be realized with the help of js.
-
publicclass DownloadWebImgTask < span class="keyword" style="margin:0px;padding:0px;border:none;color:#006699;background-color:inherit;font-weight:bold;">extends AsyncTask
{ -
-
publicstaticfinal String TAG = “DownloadWebImgTask” ;
-
-
@Override
-
protectedvoid onProgressUpdate(String… values) {
-
super.onProgressUpdate(values);
-
-
//加载下面的js代码实现单张图片的刷新
-
webView.loadUrl(“javascript:(function(){“ +
-
“var objs = document.getElementsByTagName(\”img\”); “ +
-
“for(var i=0;i
+ -
“{“
-
+ ” var imgSrc = objs[i].getAttribute(\”src_link\”); “
-
+ ” var imgOriSrc = objs[i].getAttribute(\”ori_link\”); “
-
+ ” if(imgOriSrc == \”” + values[0] + “\”){ “
-
+ ” objs[i].setAttribute(\”src\”,imgSrc);}” +
-
“}” +
-
“})()”);
-
}
-
-
@Override
-
protectedvoid onPostExecute(Void result) {
-
//这段代码只是确保所有图片都顺利的显示出来
-
webView.loadUrl(“javascript:(function(){“ +
-
“var objs = document.getElementsByTagName(\”img\”); “ +
-
“for(var i=0;i
+ -
“{“
-
+ ” var imgSrc = objs[i].getAttribute(\”src_link\”); “ +
-
” objs[i].setAttribute(\”src\”,imgSrc);” +
-
“}” +
-
“})()”);
-
super.onPostExecute(result);
-
}
-
-
@Override< /p>
-
protected Void doInBackground(String… params) {
-
URL url = null;
-
InputStream inputStream = null;
-
OutputStream outputStream = null;
-
HttpURLConnection urlCon = null;
-
-
//若传入参数为空,则直接返回
-
if(params.length == 0)
-
returnnull;
-
-
File dir = new File(Environment.getExternalStorageDirectory() + “/test/”);
-
if(!dir.exists()){
-
dir.mkdir();
-
}
-
-
for(String urlStr : params){
-
-
try {
-
-
if(urlStr == null){
-
break;
-
}
-
-
File tempFile = new File(urlStr);
-
int index = urlStr.lastIndexOf(“/”);
-
String fileName = urlStr.substring(index + 1, urlStr.length());
-
-
File file = new File(Environment.getExternalStorageDirectory() + “/test/” + fileName);
-
-
if(file.exists()){
-
continue;
-
}
-
-
try {
-
file.createNewFile();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
-
url = new URL(urlStr);
-
urlCon.setRequestMethod(“GET”);
-
urlCon.setDoInput(true);
-
urlCon.connect();
-
-
inputStream = urlCon.getInputStream();
-
outputStream = new FileOutputStream(file);
-
byte buffer[]=newbyte[1024];
-
int bufferLength = 0;
-
while((bufferLength = inputStream.read(buffer)) > 0){
-
outputStream.write(buffer, 0, bufferLength);
-
}
-
outputStream.flush();
-
publishProgress(urlStr);
-
} catch (MalformedURLException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
} catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}finally{
-
-
try {
-
if(inputStream != null){
-
inputStream.close();
-
}
-
} catch (IOException e1) {
-
// TODO Auto-generated catch block
-
e1.printStackTrace();
-
}
-
try {
-
if(outputStream != null){
-
outputStream.close();
-
}
-
} catch (IOException e) {
- < p>// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
}
-
-
}
-
-
returnnull;
-
}
-
-
}
urlCon = (HttpURLConnection)url.openConnection();
这样图片就被正常的显示出来,并且在本地已经有缓存了。
最后照例给出一个简单的demo:http://download.csdn.net/detail/chenshaoyang0011/5130931
-
public List
imgUrls = new ArrayList();
[java] view plain copy
-
Document doc = null;
-
imgUrls.clear();
-
Elements es = doc.getElementsByTag(
“img” ); -
-
for (Element e : es) {
-
String imgUrl = e.attr(“src”);
-
imgUrls.add(imgUrl);
-
String imgName;
-
File file = new File(imgUrl);
-
imgName = file.getName();
-
if(imgName.endsWith(“.gif”)){
-
e.remove();
-
}else{
-
-
String filePath = “file:///mnt/sdcard/test/” + imgName;
-
e.attr(“src”,“file:///android_asset/web_logo.png”);
-
e.attr(“src_link”, filePath);
-
e.attr(“ori_link”,imgUrl);
-
String str = “window.” + Js2JavaInterfaceName + “.setImgSrc(‘”
-
+ filePath + “‘)”;
-
e.attr(“onclick”, str);
-
}
-
}
[java] view plain copy
-
//result为解析后获得的html文本
-
webView.loadDataWithBaseURL(null, result, “text/html”, “utf-8”, null);
[java] view plain copy
-
webView.setWebViewClient(new WebViewClient(){
-
-
publicvoid onPageFinished(WebView view, String url){
-
//DownloadWebImgTask是用于下载图片的类
-
DownloadWebImgTask downloadTask = new DownloadWebImgTask();
-
-
//获取所有图片的url
-
List
urlStrs = parse r.getImgUrls(); -
-
String urlStrArray[] = new String[urlStrs.size() + 1];
-
urlStrs.toArray(urlStrArray);
-
-
//开始下载
-
downloadTask.execute(urlStrArray);
-
-
}
-
-
});
[java] view plain copy
-
publicclass DownloadWebImgTask extends AsyncTask
{ -
-
publicstaticfinal String TAG = “DownloadWebImgTask”;
-
-
@Override
-
protectedvoid onProgressUpdate(String… values) {
-
super.onProgressUpdate(values);
-
-
//加载下面的js代码实现单张图片的刷新
-
webView.loadUrl(“javascript:(function(){“ +
-
“var objs = document.getElementsByTagName(\”img\”); “ +
-
“for(var i=0;i
+ -
“{“
-
+ ” var imgSrc = objs[i].getAttribute(\”src_link\”); “
-
+ ” var imgOriSrc = objs[i].getAttribute(\”ori_link\”); “
-
+ ” if(imgOriSrc == \”” + values[0] + “\”){ “
-
+ ” objs[i].setAt tribute(\”src\”,imgSrc);}” +
-
“}” +
-
“})()”);
-
}
-
-
@Override
-
protectedvoid onPostExecute(Void result) {
-
//这段代码只是确保所有图片都顺利的显示出来
-
webView.loadUrl(“javascript:(function(){“ +
-
“var objs = document.getElementsByTagName(\”img\”); “ +
-
“for(var i=0;i
+ -
“{“
-
+ ” var imgSrc = objs[i].getAttribute(\”src_link\”); “ +
-
” objs[i].setAttribute(\”src\”,imgSrc);” +
-
“}” +
-
“})() “);
-
super.onPostExecute(result);
-
}
-
-
@Override
-
protected Void doInBackground(String… params) {
-
URL url = null;
-
InputStream inputStream = null;
-
OutputStream outputStream = null;
-
HttpURLConnection urlCon = null;
-
-
//若传入参数为空,则直接返回
-
if(params.length == 0)
-
returnnull;
-
-
File dir = new File(Environment.getExternalStorageDirec tory() + “/test/”);
-
if(!dir.exists()){
-
dir.mkdir();
-
}
-
-
for(String urlStr : params){
-
-
try {
-
-
if(urlStr == null){
-
break;
-
}
-
-
File tempFile = new File(urlStr);
-
int index = urlStr.lastIndexOf(“/”);
-
String fileName = urlStr.substring(index + 1, urlStr.length());
-
-
File file = new File(Environment.getExternalStorageDirectory() + “/test/” + fileName);
-
-
if(file.exists()){
-
continue;
-
}
-
-
try {
-
file.createNewFile();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
-
url = new URL(urlStr);
-
urlCon = (HttpURLConnection)url.openConnection();
-
urlCon.setRequestMethod(“GET”);
-
urlCon.setDoInput(true);
-
urlCon.connect();
-
-
inputStream = urlCon.getInputStream();
-
outputStream = new FileOutputStream(file);
-
byte buffer[]=newbyte[1024];
-
int bufferLength = 0;
-
while((bufferLength = inputStream.read(buffer)) > 0){
-
outputStream.write(buffer, 0, bufferLength);
-
}
-
outputStream.flush();
-
publishProgress(urlStr);
-
} catch (MalformedURLException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
} catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}finally{
-
-
try {
-
if(inputStream != null){
-
inputStream.close();
-
}
-
} catch (IOException e1) {
-
// TODO Auto-generated catch block
-
e1.printStackTrace();
-
}
-
try {
-
if(outputStre am != null){
-
outputStream.close();
-
}
-
} catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
}
-
-
}
-
-
returnnull;
-
}
-
-
}
[java] view plain copy