Android WebView 图片选择

Android WebView 图片选择

最近需要做webview选择图片,就找了一些资料,记录一下。
本文参考:Android使用WebView从相册/拍照中添加图片

自定义WebChromeClient

import android.net.Uri;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

/**
 * WebView 上传文件
 */
public class ReWebChomeClient extends WebChromeClient {

    private OpenFileChooserCallBack mOpenFileChooserCallBack;

    public ReWebChomeClient(OpenFileChooserCallBack openFileChooserCallBack) {
        mOpenFileChooserCallBack = openFileChooserCallBack;
    }

    //For Android 3.0+
    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
        mOpenFileChooserCallBack.openFileChooserCallBack(uploadMsg, acceptType);
    }

    // For Android < 3.0
    public void openFileChooser(ValueCallback uploadMsg) {
        openFileChooser(uploadMsg, "");
    }

    // For Android  > 4.1.1
    public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
        openFileChooser(uploadMsg, acceptType);
    }

    // For Android 5.0+
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
        mOpenFileChooserCallBack.showFileChooserCallBack(filePathCallback);
        return true;
    }

    public interface OpenFileChooserCallBack {
        void openFileChooserCallBack(ValueCallback uploadMsg, String acceptType);

        void showFileChooserCallBack(ValueCallback filePathCallback);
    }
}

使用ReWebChomeClient

//定义变量
private ValueCallback uploadMessage;
private ValueCallback uploadMessageAboveL;
//用来判断是否需要给WebView返回null
private int web_image = 0;
private String picFilePath;//图片保存路径
private int IDENTITY_IMAGE_REQUEST_CODE_Album = 1;//相册
private int IDENTITY_IMAGE_REQUEST_CODE_Photograph = 2;// 拍照
private int FILE_CHOOSER_RESULT_CODE = 3;//图片选择

...
//设置WebChromeClient
mWebView.setWebChromeClient(mWebChromeClient);

...

private ReWebChomeClient mWebChromeClient = new ReWebChomeClient(new ReWebChomeClient.OpenFileChooserCallBack() {
        @Override
        public void openFileChooserCallBack(ValueCallback uploadMsg, String acceptType) {//Android >=3.0
            uploadMessage = uploadMsg;
            openImageChooserActivity();
        }

        @Override
        public void showFileChooserCallBack(ValueCallback filePathCallback) {// Android >= 5.0
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
        }
    });

选择图片

  private void openImageChooserActivity() {
        web_image = 0;//判断是否已经选择了
        //自定义选择图片提示框
        AlertDialog dialog = new AlertDialog.Builder(mContext).setItems(R.array.head_type_array, (dialog1, which) -> {
        //如果点击了dialog的选项,修改变量,不要在setOnDismissListener()方法中
            web_image = 1;
            selected(which);
        }).create();
        dialog.show();
        dialog.setOnDismissListener(dialog12 -> {
            if (web_image == 0) {
                getImageWebView(null);
            }
        });
    }

    public void selected(int position) {
        switch (position) {
            case 0://相册
                getPermissionsStorage();
                break;
            case 1:// 拍照
                getPermissionsCamera();
                break;
           case 2://选择图片
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
                break;
        }
    
     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IDENTITY_IMAGE_REQUEST_CODE_Photograph) {//拍照
            if (resultCode == Activity.RESULT_OK) {
                // 添加图片
                if (picFilePath == null) {
                    picFilePath = Datas.picPathSD + BitmapUtil.pictime;
                }
                getImageWebView(picFilePath);
            } else {
                // 删除图片
                BitmapUtil.deleteTempFile(picFilePath);
                getImageWebView(null);
            }
        } else if (requestCode == IDENTITY_IMAGE_REQUEST_CODE_Album) {//相册
            if (resultCode == 1020) {
                String str_images = StringUtils.null2Length0(data.getStringExtra("images"));
                getImageWebView(str_images);
            } else {
                getImageWebView(null);
            }
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {//选择图片
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
            }
        }
    }

    private void getImageWebView(String str_image) {//将图片路径返回给webview
        if (!StringUtils.isEmpty(str_image)) {
            Uri uri = getImageContentUri(mContext, new File(str_image));
            if (uploadMessageAboveL != null) {
                Uri[] uris = new Uri[]{uri};
                uploadMessageAboveL.onReceiveValue(uris);
                uploadMessageAboveL = null;
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(uri);
                uploadMessage = null;
            }
        } else {
            if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
        }
    }

//选择图片
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                LogUtils.e("web", dataString);
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        uploadMessage = null;
        uploadMessageAboveL = null;
    }

//将文件File转成Uri
    public Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

你可能感兴趣的:(Android WebView 图片选择)