Android webviewアルバムを開いて画像を選択してサーバーにアップロード

21660 ワード

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