Android webview 打开相册选择图片并上传到服务器

package cn.hellomrhuang.webapp.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.util.ArrayList;

import cn.hellomrhuang.webapp.R;


/**
 * Created by bao on 2017/3/3.
 */

public class WebViewHelper {

    private static final int FILECHOOSER_RESULTCODE_5 = 12;
    private static final int FILECHOOSER_RESULTCODE = 13;
    private WebChromeClient.FileChooserParams  mfileChooserParams;
    ValueCallback<Uri[]> umUploadMessages;
    ValueCallback<Uri> mUploadMessage;
    private Activity mact;

    private WebView mWebView;
    private HelperWebViewClient listener;

    public WebViewHelper(Activity activity) {
        mact = activity;
    }

    public WebViewHelper(Activity activity, WebView webView) {
        mact = activity;
        mWebView = webView;
    }


    public void setWebViewClient(HelperWebViewClient listener) {
        this.listener = listener;
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void init(String url) {
        if(mWebView== null){
            mWebView = (WebView) mact.findViewById(R.id.webView);
        }


        mWebView.loadUrl(url);

        WebSettings webSettings = mWebView.getSettings();



        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 启用数据库
        webSettings.setDatabaseEnabled(true);
        String dir = mact.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        // 使用localStorage则必须打开
        webSettings.setDomStorageEnabled(true);
        // 启用地理定位
        webSettings.setGeolocationEnabled(true);
        // 设置定位的数据库路径
        webSettings.setGeolocationDatabasePath(dir);
        // 开启应用程序缓存
        webSettings.setAppCacheEnabled(true);
        String diri = mact.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        // 设置应用缓存的路径
        webSettings.setAppCachePath(diri);
        // 设置缓存的模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setLoadsImagesAutomatically(true);
        //用WebView显示图片,可使用这个参数 设置网页布局类型
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setSupportZoom(false);// 支持缩放
        webSettings.setBuiltInZoomControls(false);// 缩放控件

        // 设置WebViewClient
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (listener != null) {
                    listener.onReceivedTitle(view, url);
                }
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);


            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);


                //dialog.show();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);


            }

            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                Log.d("MyApplication", message + " -- From line " + lineNumber + " of " + sourceID);

            }
        });

        // 设置WebChromeClient
        mWebView.setWebChromeClient(new WebChromeClient() {


            // 扩充缓存的容量
            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
                                                 WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(spaceNeeded * 2);
            }

            // 配置权限(同样在WebChromeClient中实现)
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            // 扩充数据库的容量(在WebChromeClinet中实现)
            public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota,
                                                long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(estimatedSize * 2);
            }

            // 处理javascript中的alert
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                // 构建一个Builder来显示网页中的对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(mact);
                builder.setTitle("Alert");
                builder.setMessage(message);
                builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                builder.setCancelable(false);
                builder.create();
                builder.show();
                return true;
            }



            // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mact);
                builder.setTitle("confirm");
                builder.setMessage(message);
                builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                builder.setCancelable(false);
                builder.create();
                builder.show();
                return true;
            }
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

                umUploadMessages = filePathCallback;
                mfileChooserParams = fileChooserParams;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.putExtra("return-data", true);
                i.setType("image/*");
                i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                mact.startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE_5);
                return true;
            }

            // For Android 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.putExtra("return-data", true);
                i.setType("image/*");
                i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");

                mact.startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }

            // For Android > 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.putExtra("return-data", true);
                i.setType("image/*");
                i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                mact.startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }

            // Andorid 3.0 +
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.putExtra("return-data", true);
                i.setType("image/*");
                i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                mact.startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }



            @Override
            // 设置网页加载的进度条
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                Log.i("aaa", newProgress + "");
                if (listener != null) {
                    listener.onProgressChanged(view, newProgress);
                }


            }

            // 设置应用程序的标题title
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);

                if (listener != null) {
                    listener.onReceivedTitle(view, title);
                }
            }
        });

    }


    public void goBack() {
      if (mWebView.canGoBack()) {
            mWebView.goBack();

        } else {
            mact.finish();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            if (null == data){
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }else{
                Uri result = data == null || resultCode != Activity.RESULT_OK ? null
                        : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }else  if (requestCode == FILECHOOSER_RESULTCODE_5){// 5.0适配,主要是因为5.0的返回参数不同。
            // 处理5.0的callback
            if (umUploadMessages != null) {
                if (null != data) {
// 5.0的处理方式不同,要注意。
                    ArrayList<String> resultList = data
                            .getStringArrayListExtra("data");

                    umUploadMessages.onReceiveValue(
                            mfileChooserParams.parseResult(resultCode, data));
                    umUploadMessages = null;
                } else {
                    umUploadMessages.onReceiveValue(null);
                }
            }
        }
    }

    public interface HelperWebViewClient {
        void onReceivedTitle(WebView view, String title);

        void onProgressChanged(WebView view, int newProgress);

        void shouldOverrideUrlLoading(WebView view, String url);
    }
}

猜你喜欢

转载自blog.csdn.net/chinaaaaaaaaaaa/article/details/80083998