您好,登錄后才能下訂單哦!
小編給大家分享一下Android如何使用webView長按保存下載網絡圖片,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
最近發現在webView的setOnLongClickListener中可以獲取到WebView.HitTestResult,根據獲取的HitTestResult的Type來判斷做不同的處理。通過判斷Type的類型獲取點擊圖片的url,然后把圖片下載到本地,發送廣播通知系統圖庫進行更新,在系統圖庫中查看下載的圖片。運行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); } }
以上是“Android如何使用webView長按保存下載網絡圖片”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。