问题原因:

H5访问本地文件的时候, 使用的<input type="file"> ,WebView 出于安全性的考虑,是限制了以上操作。

解决办法:

重写 WebviewChromeClient 中的 openFileChooser() 和 onShowFileChooser()方法响应<input type="file">,然后使用原生代码来实现调用本地相册和拍照的功能,最后在 onActiivtyResult 把选择的图片 URI 回传给 WebviewChromeClient。

注意:

  • Android4.1系统,使用openFileChooser(),该方法在Android5.0已经被废弃。
  • Android5.0以上类型, 使用onShowFileChooser()
一,初始化操作
  ButtomDialogView mSelectImgDialog;
  public static final int INPUT_FILE_REQUEST_CODE1;
  public static final int INPUT_VIDEO_CODE = 2;
  private static final int REQUEST_CODE_ALBUM = 3;
  private ValueCallback<Uri[]> mFilePathCallback;
  private ValueCallback<Uri> nFilePathCallback;
  private String mCameraPhotoPath;
  private Uri photoURI;
  
二,重写 WebChromeClient
mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            //for  Android 4.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.d("nimei", "openFileChooser" + "----> acceptType:" + acceptType);
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                }
                nFilePathCallback = uploadMsg;
                if ("image/*".equals(acceptType)) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if ("video/*".equals(acceptType) || mWebView.getUrl().startsWith("https://ida.webank.com/") || "video/webank".equals(acceptType)) {
//                    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or选择照片
                    openSelectImgDialog();
                }
            }

            @SuppressLint("NewApi")
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                Log.d("nimei", "onShowFileChooser" + "----> acceptType:" + acceptTypes[0]);
                if (acceptTypes[0].equals("image/*")) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        //适配7.0
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            if (photoFile != null) {
                                photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                        BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
                        } else {
                            if (photoFile != null) {
                                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(photoFile));
                                Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if (acceptTypes[0].equals("video/*") || mWebView.getUrl().startsWith("https://ida.webank.com/") || acceptTypes[0].equals("video/webank")) {
//                  录制视频
//                       Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or选择照片
                    openSelectImgDialog();
                }
                return true;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }
        });
三,选择相机or选择相册
public void openSelectImgDialog() {
        View ShippingInformationView = LayoutInflater.from(NewFreshJNWebViewActivity.this).inflate(R.layout.layout_shipping_inf_dialog, null);
        mSelectImgDialog = new ButtomDialogView(NewFreshJNWebViewActivity.this, ShippingInformationView, false, false);

        TextView tv_supplier_selection_address = (TextView) ShippingInformationView.findViewById(R.id.tv_supplier_selection_address);
        tv_supplier_selection_address.setText("拍照");
        TextView tv_cancel = (TextView) ShippingInformationView.findViewById(R.id.tv_cancel);
        TextView tv_choose_consignee = (TextView) ShippingInformationView.findViewById(R.id.tv_choose_consignee);
        tv_choose_consignee.setText("相册");
        //拍照
        tv_supplier_selection_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        Log.e("TAG", "Unable to create Image File", ex);
                    }
                    //适配7.0
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        if (photoFile != null) {
                            photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                    BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        }
                    } else {
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                }
                startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);

            }
        });
        //相册选择照片
        tv_choose_consignee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);
            }
        });
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                //一定要返回null,否则<input type='file'>
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                    nFilePathCallback = null;
                }
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                    mFilePathCallback = null;

                }
            }
        });
        mSelectImgDialog.show();
    }
    
 private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir      /* 文件夹 */
        );
        mCameraPhotoPath = image.getAbsolutePath();
        return image;
    }
    
四,选择相机or选择相册
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri[] results = null;
        Uri mUri = null;
        if (resultCode == Activity.RESULT_OK && requestCode == INPUT_FILE_REQUEST_CODE) {
            if (data == null) {
                if (Build.VERSION.SDK_INT > M) {
                    mUri = photoURI;
                    results = new Uri[]{mUri};
                } else {
                    if (mCameraPhotoPath != null) {
                        mUri = Uri.parse(mCameraPhotoPath);
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                }
            } else {
                Uri nUri = data.getData();
                if (nUri != null) {
                    mUri = nUri;
                    results = new Uri[]{nUri};
                }
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == INPUT_VIDEO_CODE) { //录制视频
            mUri = data.getData();
            results = new Uri[]{mUri};
        } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ALBUM) {
            //选择相册
            if (data != null) {
                mUri = data.getData();
            }
            results = new Uri[]{mUri};
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            nFilePathCallback.onReceiveValue(mUri);
            nFilePathCallback = null;
            return;
        } else {
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
            return;
        }
    }
完整代码
package com.xxxxx;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xxxxx.plugin.JsApi;
import com.xxxxx.plugin.WebviewEvent;
import com.xxxxx.ui.BaseActivity;
import com.xxxxx.ui.activity.JNChooseConsigneeSupplierActivity;
import com.xxxxx.ui.activity.JNTakeOrderActivity;
import com.xxxxx.ui.widget.ButtomDialogView;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import wendu.dsbridge.DWebView;

import static android.os.Build.VERSION_CODES.M;

/**
 * webview activity
 */
public class NewFreshJNWebViewActivity extends BaseActivity {
    public static final String TAG = "NewFreshJNWebViewActivity";
    private DWebView mWebView;
    public String url, title, name;
    TextView tv_title;
    ButtomDialogView mSelectImgDialog;
    public static final int INPUT_FILE_REQUEST_CODE = 1;
    public static final int INPUT_VIDEO_CODE = 2;
    private static final int REQUEST_CODE_ALBUM = 3;
    private ValueCallback<Uri[]> mFilePathCallback;
    private ValueCallback<Uri> nFilePathCallback;
    private String mCameraPhotoPath;
    private Uri photoURI;
    ImageView img_close;

    @SuppressLint("LongLogTag")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jnface_verify);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        Log.d(TAG, url);
        initWebView();
        LinearLayout lay_back = (LinearLayout) findViewById(R.id.lay_back);
        img_close = (ImageView) findViewById(R.id.img_close);
        img_close.setOnClickListener(v -> {
            NewFreshJNWebViewActivity.this.finish();
            JSONObject newMap = new JSONObject();
            try {
                newMap.put("name", name);
                newMap.put("type", "click");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
        });
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(!TextUtils.isEmpty(title) ? title : "江楠鲜品");
        lay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void initWebView() {
        mWebView = (DWebView) findViewById(R.id.main_webview);
        WBH5FaceVerifySDK.getInstance().setWebViewSettings(mWebView, getApplicationContext());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        mWebView.addJavascriptObject(new JsApi(NewFreshJNWebViewActivity.this), "freshjn.webview");
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            //for  Android 4.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.d("nimei", "openFileChooser" + "----> acceptType:" + acceptType);
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                }
                nFilePathCallback = uploadMsg;
                if ("image/*".equals(acceptType)) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if ("video/*".equals(acceptType) || mWebView.getUrl().startsWith("https://ida.webank.com/") || "video/webank".equals(acceptType)) {
//                    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or选择照片
                    openSelectImgDialog();
                }
            }

            @SuppressLint("NewApi")
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                Log.d("nimei", "onShowFileChooser" + "----> acceptType:" + acceptTypes[0]);
                if (acceptTypes[0].equals("image/*")) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        //适配7.0
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            if (photoFile != null) {
                                photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                        BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
                        } else {
                            if (photoFile != null) {
                                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(photoFile));
                                Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if (acceptTypes[0].equals("video/*") || mWebView.getUrl().startsWith("https://ida.webank.com/") || acceptTypes[0].equals("video/webank")) {
//                  录制视频
//                       Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or选择照片
                    openSelectImgDialog();
                }
                return true;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }
        });

        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }

//        mWebView.loadUrl("http://qatest.fabigbig.com:8887/fddAuthenticationService/app/index.html#/agreement?id=2c9282926830c337016835d477e30249&operation=0&token=1721cf9e601342eaa7951727f961d583");
    }

    // 相机 或者 相册
    public void openSelectImgDialog() {
        View ShippingInformationView = LayoutInflater.from(NewFreshJNWebViewActivity.this).inflate(R.layout.layout_shipping_inf_dialog, null);
        mSelectImgDialog = new ButtomDialogView(NewFreshJNWebViewActivity.this, ShippingInformationView, false, false);

        TextView tv_supplier_selection_address = (TextView) ShippingInformationView.findViewById(R.id.tv_supplier_selection_address);
        tv_supplier_selection_address.setText("拍照");
        TextView tv_cancel = (TextView) ShippingInformationView.findViewById(R.id.tv_cancel);
        TextView tv_choose_consignee = (TextView) ShippingInformationView.findViewById(R.id.tv_choose_consignee);
        tv_choose_consignee.setText("相册");
        //拍照
        tv_supplier_selection_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 调用后置摄像头
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        Log.e("TAG", "Unable to create Image File", ex);
                    }
                    //适配7.0
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        if (photoFile != null) {
                            photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                    BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        }
                    } else {
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                }
                startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);

            }
        });
        //相册选择照片
        tv_choose_consignee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);
            }
        });
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                //一定要返回null,否则<input type='file'>
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                    nFilePathCallback = null;
                }
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                    mFilePathCallback = null;

                }
            }
        });
        mSelectImgDialog.show();
    }


    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir      /* 文件夹 */
        );
        mCameraPhotoPath = image.getAbsolutePath();
        return image;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri[] results = null;
        Uri mUri = null;
        if (resultCode == Activity.RESULT_OK && requestCode == INPUT_FILE_REQUEST_CODE) {
            if (data == null) {
                if (Build.VERSION.SDK_INT > M) {
                    mUri = photoURI;
                    results = new Uri[]{mUri};
                } else {
                    if (mCameraPhotoPath != null) {
                        mUri = Uri.parse(mCameraPhotoPath);
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                }
            } else {
                Uri nUri = data.getData();
                if (nUri != null) {
                    mUri = nUri;
                    results = new Uri[]{nUri};
                }
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == INPUT_VIDEO_CODE) { //录制视频
            mUri = data.getData();
            results = new Uri[]{mUri};
        } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ALBUM) {
            //选择相册
            if (data != null) {
                mUri = data.getData();
            }
            results = new Uri[]{mUri};
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            nFilePathCallback.onReceiveValue(mUri);
            nFilePathCallback = null;
            return;
        } else {
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
            return;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            JSONObject newMap = new JSONObject();
            try {
                newMap.put("name", name);
                newMap.put("type", "click");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else {

                JSONObject newMap = new JSONObject();
                try {
                    newMap.put("name", name);
                    newMap.put("type", "click");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //注册订阅者
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        //注销注册
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebviewEvent(WebviewEvent event) {
        if (event.getmObject() != null && event.getmType() != null) {
            if (event.getmType().equals("close")) {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        if (mSelectImgDialog != null && mSelectImgDialog.isShowing()) {
            mSelectImgDialog.dismiss();
            mSelectImgDialog = null;
        }
    }
}



七號座先生
17 声望0 粉丝