时间:2021-01-28 10:25:26 | 栏目:Android代码 | 点击:次
本文实例为大家分享了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); } }