1. 程式人生 > >Android使用webView長按儲存下載網路圖片

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);
    }

}
/**
 * 圖片下載的工具類
 */
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("/");
                 fileName = split[split.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);
                    }

                    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);
    }
}