欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用webView长按保存下载网络图片

程序员文章站 2022-07-06 14:34:45
本文实例为大家分享了android使用webview长按保存下载网络图片的具体代码,供大家参考,具体内容如下 最近发现在webview的setonlongclicklis...

本文实例为大家分享了android使用webview长按保存下载网络图片的具体代码,供大家参考,具体内容如下

最近发现在webview的setonlongclicklistener中可以获取到webview.hittestresult,根据获取的hittestresult的type来判断做不同的处理。通过判断type的类型获取点击图片的url,然后把图片下载到本地,发送广播通知系统图库进行更新,在系统图库中查看下载的图片。运行demo在网页中对图片做长按点击即可下载网络图片

直接上代码:

下面附有demo下载:点击打开链接

package demo.sam.webview_demo; 

import android.app.activity; 
import android.app.dialog; 
import android.content.context; 
import android.content.dialoginterface; 
import android.content.intent; 
import android.net.uri; 
import android.os.handler; 
import android.os.message; 
import android.provider.mediastore; 
import android.support.v7.app.alertdialog; 
import android.support.v7.app.appcompatactivity; 
import android.os.bundle; 
import android.text.editable; 
import android.util.log; 
import android.view.keyevent; 
import android.view.view; 
import android.webkit.webchromeclient; 
import android.webkit.webresourcerequest; 
import android.webkit.websettings; 
import android.webkit.webview; 
import android.webkit.webviewclient; 
import android.widget.button; 
import android.widget.edittext; 
import android.widget.progressbar; 
import android.widget.toast; 

import java.io.filenotfoundexception; 

public class mainactivity extends activity { 

 private progressbar progress; 
 private webview webview; 
 private edittext edittext; 
 private button click; 
 private context context; 


 @override 
 protected void oncreate(bundle savedinstancestate) { 
  super.oncreate(savedinstancestate); 
  setcontentview(r.layout.activity_main); 
  context= this; 
  initview(); 
  initdata(); 
  initlistener(); 



 } 

 private void initdata() { 
  websettings settings = webview.getsettings(); 
  settings.setjavascriptenabled(true); 
  settings.setusewideviewport(true);//设置此属性,可任意比例缩放 
  settings.setloadwithoverviewmode(true); 
  // 使页面支持缩放 
  settings.setbuiltinzoomcontrols(true); 
  settings.setsupportzoom(true); 
  //支持自动加载图片 
  settings.setloadsimagesautomatically(true); 
  settings.setlayoutalgorithm(websettings.layoutalgorithm.normal);// 排版适应屏幕 
  // 缩放按钮 
  settings.setdisplayzoomcontrols(false); 

  webview.setwebviewclient(new webviewclient(){ 

   // 页面在当前页面跳转 
   @override 
   public boolean shouldoverrideurlloading(webview view, webresourcerequest request) { 
    return super.shouldoverrideurlloading(view, request); 
   } 

   // 页面加载结束 
   @override 
   public void onpagefinished(webview view, string url) { 
    super.onpagefinished(view, url); 
    if(progress!=null){ 
     progress.setvisibility(view.gone); 
    } 
   } 
  }); 

 } 

 private void initview() { 
  progress = (progressbar) findviewbyid(r.id.progress); 
  webview = (webview) findviewbyid(r.id.webview); 
  edittext = (edittext) findviewbyid(r.id.url); 
  click = (button) findviewbyid(r.id.click); 
 } 

 private void initlistener() { 
  // 网页加载进度显示 
  webview.setwebchromeclient(new webchromeclient(){ 
   @override 
   public void onprogresschanged(webview view, int newprogress) { 
    super.onprogresschanged(view, newprogress); 
    progress.setvisibility(view.visible); 
    progress.setprogress(newprogress); 
   } 
  }); 

  click.setonclicklistener(new view.onclicklistener() { 
   @override 
   public void onclick(view view) { 
    log.e("输入的网站",edittext.gettext().tostring().trim()); 
    webview.loadurl(edittext.gettext().tostring().trim()); 
   } 
  }); 

  // 长按点击事件 
  webview.setonlongclicklistener(new view.onlongclicklistener() { 
   @override 
   public boolean onlongclick(view view) { 
    final webview.hittestresult hittestresult = webview.gethittestresult(); 
    // 如果是图片类型或者是带有图片链接的类型 
    if(hittestresult.gettype()== webview.hittestresult.image_type|| 
      hittestresult.gettype()== webview.hittestresult.src_image_anchor_type){ 
     // 弹出保存图片的对话框 
     alertdialog.builder builder = new alertdialog.builder(context); 
     builder.settitle("提示"); 
     builder.setmessage("保存图片到本地"); 
     builder.setpositivebutton("确认", new dialoginterface.onclicklistener() { 
      @override 
      public void onclick(dialoginterface dialoginterface, int i) { 
       string url = hittestresult.getextra(); 
       // 下载图片到本地 
       downpicutil.downpic(url, new downpicutil.downfinishlistener(){ 

        @override 
        public void getdownpath(string s) { 
         toast.maketext(context,"下载完成",toast.length_long).show(); 
         message msg = message.obtain(); 
         msg.obj=s; 
         handler.sendmessage(msg); 
        } 
       }); 

      } 
     }); 
     builder.setnegativebutton("取消", new dialoginterface.onclicklistener() { 
      // 自动dismiss 
      @override 
      public void onclick(dialoginterface dialoginterface, int i) { 
      } 
     }); 
     alertdialog dialog = builder.create(); 
     dialog.show(); 
    } 
    return true; 
   } 
  }); 

  webview.loadurl("http://www.baidu.com"); 
 } 

 handler handler =new handler(){ 
  @override 
  public void handlemessage(message msg) { 
   super.handlemessage(msg); 
   string picfile = (string) msg.obj; 
   string[] split = picfile.split("/"); 
   string filename = split[split.length-1]; 
   try { 
    mediastore.images.media.insertimage(getapplicationcontext().getcontentresolver(), picfile, filename, null); 
   } catch (filenotfoundexception e) { 
    e.printstacktrace(); 
   } 
   // 最后通知图库更新 
   getapplicationcontext().sendbroadcast(new intent(intent.action_media_scanner_scan_file, uri.parse("file://" + picfile))); 
   toast.maketext(context,"图片保存图库成功",toast.length_long).show(); 
  } 
 }; 


 // 监听返回键返回网页的上一层 
 @override 
 public boolean onkeydown(int keycode, keyevent event) { 
  if(keycode == keyevent.keycode_back && webview.cangoback()){ 
   if(webview != null){ 
    webview.goback(); 
    return true; 
   } 
  } 
  return super.onkeydown(keycode, event); 
 } 

} 

图片下载的工具类

import android.os.asynctask; 
import android.os.environment; 
import android.util.log; 

import java.io.file; 
import java.io.filenotfoundexception; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.net.url; 
import java.util.random; 

/** 
 * 图片下载的工具类 
 */ 
public class downpicutil { 

 /** 
  *下载图片,返回图片的地址 
  * @param url 
  */ 
 public static void downpic(string url,downfinishlistener downfinishlistener){ 
  // 获取存储卡的目录 
  string filepath = environment.getexternalstoragedirectory().getpath(); 
  file file = new file(filepath+file.separator+"webviewcache"); 
  if(!file.exists()){ 
   file.mkdir(); 
  } 

  loadpic(file.getpath(),url,downfinishlistener); 

 } 

 private static void loadpic(final string filepath, final string url, final downfinishlistener downfinishlistener) { 
  log.e("下载图片的url",url); 
  new asynctask<void,void,string>(){ 
   string filename; 
   inputstream is; 
   outputstream out; 

   @override 
   protected string doinbackground(void... voids) { 

    // 下载文件的名称 
    string[] split = url.split("/"); 
    string newstring = split[split.length - 1]; 
    filename =newstring.substring(newstring.length()-20,newstring.length()-1) ; 
    // 创建目标文件,不是文件夹 
    file picfile = new file(filepath + file.separator + filename); 
    if(picfile.exists()){ 
     return picfile.getpath(); 
    } 

    try { 
     url picurl = new url(url); 
     //通过图片的链接打开输入流 
     is = picurl.openstream(); 
     if(is==null){ 
      return null; 
     } 
     out = new fileoutputstream(picfile); 
     byte[] b=new byte[1024]; 
     int end ; 
     while ((end=is.read(b))!=-1){ 
      out.write(b,0,end); 
     } 

     log.e("ok??","----------"); 
     if(is!=null){ 
      is.close(); 
     } 

     if(out!=null){ 
      out.close(); 
     } 

    } catch (filenotfoundexception e) { 
     e.printstacktrace(); 
    } catch (ioexception e) { 
     e.printstacktrace(); 
    } 



    return picfile.getpath(); 
   } 

   @override 
   protected void onpostexecute(string s) { 
    super.onpostexecute(s); 
    if(s!=null){ 
     downfinishlistener.getdownpath(s); 
    } 
   } 
  }.execute(); 
 } 
 //下载完成回调的接口 
 public interface downfinishlistener{ 

  void getdownpath(string s); 
 } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。