andriod开发 webview调照相机拍照上传及文件选择等多种方式

序言:这个功能是产品经理要求要的,本来是直接选择文件目录,研究了2天,总算成功,我们项目是嵌入式开发,话不多说,上代码。。。

1、服务端jsp代码如下:


2、安卓客户端代码(WebViewActivity)如下:

private ValueCallback mUploadMessage;
private ValueCallback mUploadCallbackAboveL;
private Uri imageUri;
private String imageFilePath;
private final static int FILECHOOSER_RESULTCODE = 10000;

mWebView.setWebChromeClient(new WebChromeClient() {
        public void openFileChooser(ValueCallback uploadMsg) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }
        public void openFileChooser(ValueCallback uploadMsg, String acceptType ) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }
        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.setType("*/*");
            startActivityForResult( Intent.createChooser( i, "File Browser" ), WebViewActivity.FILECHOOSER_RESULTCODE );
        }
        public boolean onShowFileChooser (WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            startActivityForResult(
                    Intent.createChooser(createDefaultOpenableIntent(), "File Browser"),
                    FILECHOOSER_RESULTCODE);
            return true;
        }
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            //创建一个Builder来显示网页中的对话框
            new AlertDialog.Builder(WebViewActivity.this).setTitle("信息提示").setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if(message.contains("重新登录"))
                                WebViewActivity.this.startActivity(new Intent(WebViewActivity.this,WelcomeActivity.class));
                            else
                                result.confirm();
                        }
                    }).setCancelable(false).show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(WebViewActivity.this).setTitle("信息提示").setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            }).setCancelable(false).show();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    });

private Intent createDefaultOpenableIntent() {
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setType("*/*");
    Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),createImageIntent());
    chooser.putExtra(Intent.EXTRA_INTENT, i);
    return chooser;
}

private Intent createChooserIntent(Intent... intents) {
    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
    chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
    return chooser;
}
private Intent createCameraIntent() {
    // 指定拍照存储位置的方式调起相机
    String filePath = Environment.getExternalStorageDirectory() + File.separator
            + Environment.DIRECTORY_PICTURES + File.separator;
    String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
    imageUri = Uri.fromFile(new File(filePath + fileName));
    imageFilePath = filePath + fileName;

    Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

    return captureIntent;
}

private Intent createCamcorderIntent() {
    return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
}

private Intent createImageIntent() {
    Intent Photo = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    return Photo;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILECHOOSER_RESULTCODE) {
        // 经过上边(1)、(2)两个赋值操作,此处即可根据其值是否为空来决定采用哪种处理方法
        if (mUploadMessage != null) {
            chooseBelow(resultCode, data);
        } else if (mUploadCallbackAboveL != null) {
            chooseAbove(resultCode, data);
        } else {
            Toast.makeText(this, "发生错误", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 * Android API < 21(Android 5.0)版本的回调处理
 * @param resultCode 选取文件或拍照的返回码
 * @param data 选取文件或拍照的返回结果
 */
private void chooseBelow(int resultCode, Intent data) {
    if (RESULT_OK == resultCode) {
        if (data != null) {
            // 这里是针对文件路径处理
            Uri uri = data.getData();
            if (uri != null) {
                mUploadMessage.onReceiveValue(uri);
            } else {
                mUploadMessage.onReceiveValue(null);
            }
        } else {
            // 以指定图像存储路径的方式调起相机,成功后返回data为空
            File mFile = new File(imageFilePath);
            Uri mUri = null;
            try {
                if (ActivityCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(WebViewActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
                mUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mFile.getAbsolutePath(), mFile.getName(), mFile.getName()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            mUploadCallbackAboveL.onReceiveValue(new Uri[]{mUri});
        }
    } else {
        mUploadMessage.onReceiveValue(null);
    }
    mUploadMessage = null;
}

/**
 * Android API >= 21(Android 5.0) 版本的回调处理
 * @param resultCode 选取文件或拍照的返回码
 * @param data 选取文件或拍照的返回结果
 */
private void chooseAbove(int resultCode, Intent data) {
    if (RESULT_OK == resultCode) {
        if (data != null) {
            // 这里是针对从文件中选图片的处理
            Uri[] results;
            Uri uriData = data.getData();
            if (uriData != null) {
                results = new Uri[]{uriData};
                mUploadCallbackAboveL.onReceiveValue(results);
            } else {
                mUploadCallbackAboveL.onReceiveValue(null);
            }
        } else {
            File mFile = new File(imageFilePath);
            Uri mUri = null;
            try {
                if (ActivityCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(WebViewActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
                mUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mFile.getAbsolutePath(), mFile.getName(), mFile.getName()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            mUploadCallbackAboveL.onReceiveValue(new Uri[]{mUri});
        }
    } else {
        mUploadCallbackAboveL.onReceiveValue(null);
    }
    mUploadCallbackAboveL = null;
}

andriod开发 webview调照相机拍照上传及文件选择等多种方式_第1张图片

你可能感兴趣的:(安卓开发)