小編給大家分享一下Android如何使用webView長(zhǎng)按保存下載網(wǎng)絡(luò)圖片,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
堅(jiān)守“ 做人真誠(chéng) · 做事靠譜 · 口碑至上 · 高效敬業(yè) ”的價(jià)值觀,專業(yè)網(wǎng)站建設(shè)服務(wù)10余年為成都成都OPP膠袋小微創(chuàng)業(yè)公司專業(yè)提供成都定制網(wǎng)頁(yè)設(shè)計(jì)營(yíng)銷網(wǎng)站建設(shè)商城網(wǎng)站建設(shè)手機(jī)網(wǎng)站建設(shè)小程序網(wǎng)站建設(shè)網(wǎng)站改版,從內(nèi)容策劃、視覺(jué)設(shè)計(jì)、底層架構(gòu)、網(wǎng)頁(yè)布局、功能開(kāi)發(fā)迭代于一體的高端網(wǎng)站建設(shè)服務(wù)。
最近發(fā)現(xiàn)在webView的setOnLongClickListener中可以獲取到WebView.HitTestResult,根據(jù)獲取的HitTestResult的Type來(lái)判斷做不同的處理。通過(guò)判斷Type的類型獲取點(diǎn)擊圖片的url,然后把圖片下載到本地,發(fā)送廣播通知系統(tǒng)圖庫(kù)進(jìn)行更新,在系統(tǒng)圖庫(kù)中查看下載的圖片。運(yùn)行Demo在網(wǎng)頁(yè)中對(duì)圖片做長(zhǎng)按點(diǎn)擊即可下載網(wǎng)絡(luò)圖片
直接上代碼:
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);//設(shè)置此屬性,可任意比例縮放 settings.setLoadWithOverviewMode(true); // 使頁(yè)面支持縮放 settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); //支持自動(dòng)加載圖片 settings.setLoadsImagesAutomatically(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版適應(yīng)屏幕 // 縮放按鈕 settings.setDisplayZoomControls(false); webView.setWebViewClient(new WebViewClient(){ // 頁(yè)面在當(dāng)前頁(yè)面跳轉(zhuǎn) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } // 頁(yè)面加載結(jié)束 @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() { // 網(wǎng)頁(yè)加載進(jìn)度顯示 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("輸入的網(wǎng)站",editText.getText().toString().trim()); webView.loadUrl(editText.getText().toString().trim()); } }); // 長(zhǎng)按點(diǎn)擊事件 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){ // 彈出保存圖片的對(duì)話框 AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示"); builder.setMessage("保存圖片到本地"); builder.setPositiveButton("確認(rèn)", 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() { // 自動(dòng)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(); } // 最后通知圖庫(kù)更新 getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + picFile))); Toast.makeText(context,"圖片保存圖庫(kù)成功",Toast.LENGTH_LONG).show(); } }; // 監(jiān)聽(tīng)返回鍵返回網(wǎng)頁(yè)的上一層 @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){ // 獲取存儲(chǔ)卡的目錄 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(){ 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) ; // 創(chuàng)建目標(biāo)文件,不是文件夾 File picFile = new File(filePath + File.separator + fileName); if(picFile.exists()){ return picFile.getPath(); } try { URL picUrl = new URL(url); //通過(guò)圖片的鏈接打開(kāi)輸入流 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(); } //下載完成回調(diào)的接口 public interface DownFinishListener{ void getDownPath(String s); } }
以上是“Android如何使用webView長(zhǎng)按保存下載網(wǎng)絡(luò)圖片”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!