美文网首页
HTML调用原生相册

HTML调用原生相册

作者: Il_mondo | 来源:发表于2018-08-04 11:53 被阅读22次
    public class FileChooser {
    
        private static FileChooser FILE_CHOOSER;
    
        private Activity mActivity;
        private final int FILE_SELECT_CODE = 1;
        private ValueCallback<Uri> mUploadCallbackBelow;
        private ValueCallback<Uri[]> mUploadCallbackAboveL;
    
        public static FileChooser get(Activity activity){
    
            if (FILE_CHOOSER == null){
                FILE_CHOOSER = new FileChooser(activity);
            }
    
            return FILE_CHOOSER;
        }
    
        public FileChooser(Activity activity) {
            mActivity = activity;
        }
    
        /**
         * API >= 21(Android 5.0.1)
         */
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            takeImage();
            return true;
        }
    
        /**
         * 16(Android 4.1.2) <= 20(Android 4.4W.2)
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadCallbackBelow = uploadMsg;
            takeImage();
        }
    
        private void takeImage() {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            mActivity.startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_SELECT_CODE);
        }
    
        // 接收图片回调
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null) {
                if (mUploadCallbackBelow != null) {
                    chooseBelow(resultCode, data);
                } else if (mUploadCallbackAboveL != null) {
                    chooseAbove(resultCode, data);
                }
            }
        }
    
        /**
         * Android API < 21(Android 5.0)
         */
        private void chooseAbove(int resultCode, Intent data) {
            Uri uriData = data.getData();
            if (uriData != null) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{uriData});
            } else {
                mUploadCallbackAboveL.onReceiveValue(null);
            }
        }
    
        /**
         * 16(Android 4.1.2) <= 20(Android 4.4W.2)
         */
        private void chooseBelow(int resultCode, Intent data) {
            Uri uri = data.getData();
            if (uri != null) {
                mUploadCallbackBelow.onReceiveValue(uri);
            } else {
                mUploadCallbackBelow.onReceiveValue(null);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:HTML调用原生相册

          本文链接:https://www.haomeiwen.com/subject/lftmvftx.html