H5通过JS注入调用android摄像头(android部分代码)

public class ControlFragment extends BaseFragment {
    private static ProgressWebView webView;
    private WebSettings mSettings;
    private String capturePath;
    private String cameraId;
    private String type = null;
    public final int TRYPLAY = 99;// 拍照
    public final int DIAOYONG = 89;// 直接调用
    public final int FILECHOOSER_RESULTCODE = 11;
    public final int REQ_CAMERA = 12;
    public final int REQ_CHOOSE = 13;
    private final int SELECT_RESULT_CODE = 6;
    public final int NONE = 0;
    private final int RESULT_OK = 0;
    private File picture;
    private ValueCallback<Uri> mUploadMessage;
    private Uri result;
    String compressPath = "";
    String imagePaths;

    @Override
    protected int getContentResId() {
    
    return R.layout.fragment_web;
    }

    @Override
    protected void onFindView(View rootView) {
    super.onFindView(rootView);
    webView = (ProgressWebView) rootView.findViewById(R.id.webview);
    mSettings = webView.getSettings();
    // WebView先不要自动加载图片
    mSettings.setJavaScriptEnabled(true);
    mSettings.setBuiltInZoomControls(true);
    mSettings.setSupportZoom(true);
    mSettings
        .setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    mSettings.setUseWideViewPort(true);
    mSettings.setGeolocationEnabled(true);
    mSettings.setDomStorageEnabled(true);
    mSettings.setAppCacheMaxSize(1024 * 1024 * 8);

    webView.requestFocus();
    webView.setScrollBarStyle(0);
    webView.addJavascriptInterface(new WebUtils(), "JavaScriptInterface");
    // webView.setChromeClient(new myWebChromeClient());
    webView.setWebChromeClient(new myWebChromeClient());
    webView.setWebViewClient(new MyWebClient(getActivity()));
    webView.loadUrl(setloadUrl());

    }

    /**
     * @auther xt 回调结果
     * @date 2016年3月29日09:49:26
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (null == mUploadMessage)
        return;
    Uri uri = null;
    if (requestCode == REQ_CAMERA) {
        afterOpenCamera();
        String media;
        try {
        media = MediaStore.Images.Media.insertImage(getActivity()
            .getContentResolver(), imagePaths, "", "");
        result = Uri.parse(media);
        } catch (FileNotFoundException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
        }

        uri = result;
        mUploadMessage.onReceiveValue(uri);
        mUploadMessage = null;
    } else if (requestCode == REQ_CHOOSE) {
        if (data != null) {
        uri = afterChosePic(data);
        mUploadMessage.onReceiveValue(uri);
        mUploadMessage = null;
        } else {
        mUploadMessage.onReceiveValue(null);
        mUploadMessage = null;
        }

    }
    if (resultCode == NONE) {
        // mUploadMessage = null;
        // return;
    }
    if (requestCode == TRYPLAY) {
        // 设置文件保存路径这里放在跟目录下
        picture = new File(Environment.getExternalStorageDirectory()
            + "/temp.jpg");
        File extras = picture;
        if (extras != null) {
        String picName = bitmapToBase64(ratio(
            Environment.getExternalStorageDirectory() + "/temp.jpg",
            200f, 200f));
        String pictureId = "$('#'+'" + cameraId + "').attr('src', '"
            + picName + "');";
        webView.loadUrl("javascript:" + pictureId);
        }
        // 读取相册缩放图片
    }
    if (requestCode == SELECT_RESULT_CODE) {
        String picPathString = null;
        // Uri uri = data.getData();
        Cursor cursor = getActivity().getContentResolver().query(uri, null,
            null, null, null);
        if (cursor == null) {
        picPathString = uri.getPath();
        } else {
        cursor.moveToFirst();
        String imgPath = cursor.getString(1);
        picPathString = imgPath;
        }
        String picName = bitmapToBase64(ratio(picPathString, 200f, 200f));
        // upCameraApi(picPathString);
    }
    if (requestCode == DIAOYONG) {
        if (null == mUploadMessage) {
        return;
        }
        if (mUploadMessage != null) {
        if (data != null) {
            mUploadMessage.onReceiveValue(data.getData());
            mUploadMessage = null;
        } else {
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
        }

        } else {
        mUploadMessage.onReceiveValue(null);
        mUploadMessage = null;
        }
    }

    }

    /**
     * @auther xietian 弹相关的dialog
     * @date 2016年3月29日09:49:26
     * @param
     * @return void
     */
    public void showImagePickDialog() {

    String title = "获取图片方式";

    String[] choices = new String[] { "拍照", "相册" };

    new AlertDialog.Builder(getActivity()).setTitle(title)

    .setItems(choices, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {

        dialog.dismiss();
        switch (which) {
        case 0:
            openCarcme();
            break;

        case 1:
            chosePic();
            break;
        default:
            mUploadMessage = null;
            break;

        }
        compressPath = Environment.getExternalStorageDirectory()
            .getPath() + "/fuiou_wmp/temp";
        new File(compressPath).mkdirs();
        compressPath = compressPath + File.separator + "compress.jpg";

        }

    }).setNegativeButton("返回", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {

        dialog.dismiss();
        switch (which) {
        default:
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
            break;

        }
        compressPath = Environment.getExternalStorageDirectory()
            .getPath() + "/fuiou_wmp/temp";
        new File(compressPath).mkdirs();
        compressPath = compressPath + File.separator + "compress.jpg";

        }

    }).setCancelable(false).show();
    }

    Uri cameraUri;
    private String mediaS;
    private String mediaStr;

    /**
     * @auther xt 打开照相机
     * @date 2016年5月12日
     * @param
     * @return void
     */
    private void openCarcme() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    imagePaths = Environment.getExternalStorageDirectory().getPath()
        + "/fuiou_wmp/temp/" + (System.currentTimeMillis() + ".jpg");
    // // 必须确保文件夹路径存在,否则拍照后无法完成回调
    // File vFile = new File(imagePaths);
    // if (!vFile.exists()) {
    // File vDirPath = vFile.getParentFile();
    // vDirPath.mkdirs();
    // } else {
    // if (vFile.exists()) {
    // vFile.delete();
    // }
    // }
    //
    // cameraUri = Uri.fromFile(vFile);
    // intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
    // startActivityForResult(intent, REQ_CAMERA);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
        Environment.getExternalStorageDirectory(), "/fuiou_wmp/temp/"
            + (System.currentTimeMillis() + ".jpg"))));
    getRootFragment().startActivityForResult(
        Intent.createChooser(intent, "File Chooser"), REQ_CAMERA);
    }

    /**
     * @auther xt 处理拍照结束后
     * @date 2016年5月12日
     * @param
     * @return void
     */
    private void afterOpenCamera() {
    File f = new File(imagePaths);
    addImageGallery(f);
    // File newFile = FileUtils.compressFile(f.getPath(), compressPath);
    }

    /**
     * 解决拍照后在相册中找不到的问题
     *
     * @auther xt
     * @date 2016年5月12日
     * @param
     * @return void
     */
    private void addImageGallery(File file) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    getActivity().getContentResolver().insert(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    /**
     * 本地相册选择图片
     *
     * @auther xt
     * @date 2016年5月12日
     * @param
     */
    private void chosePic() {
    FileUtils.delFile(compressPath);
    Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
    String IMAGE_UNSPECIFIED = "image/*";
    innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
    Intent wrapperIntent = Intent.createChooser(innerIntent, null);
    // startActivityForResult(wrapperIntent, REQ_CHOOSE);
    getRootFragment()
        .startActivityForResult(
            Intent.createChooser(wrapperIntent, "File Chooser"),
            REQ_CHOOSE);
    }

    /**
     * 选择照片后结束
     *
     * @auther xt
     * @date 2016年5月12日
     * @param
     */
    private Uri afterChosePic(Intent data) {

    // 获取图片的路径:
    String[] proj = { MediaStore.Images.Media.DATA };
    // 好像是android多媒体数据库的封装接口,具体的看Android文档
    @SuppressWarnings("deprecation")
    Cursor cursor = getActivity().managedQuery(data.getData(), proj, null,
        null, null);
    if (cursor == null) {
        // Toast.makeText(this,
        // "上传的图片仅支持png或jpg格式",Toast.LENGTH_SHORT).show();
        return null;
    }
    // 按我个人理解 这个是获得用户选择的图片的索引值
    int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    // 将光标移至开头 ,这个很重要,不小心很容易引起越界
    cursor.moveToFirst();
    // 最后根据索引值获取图片路径
    String path = cursor.getString(column_index);
    if (path != null
        && (path.endsWith(".png") || path.endsWith(".PNG")
            || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
        try {
        mediaStr = MediaStore.Images.Media.insertImage(getActivity()
            .getContentResolver(), path, "", "");
        } catch (FileNotFoundException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
        }
        result = Uri.parse(mediaStr);

        // File newFile = FileUtils.compressFile(path, compressPath);
        return result;
    } else {
        // Toast.makeText(this,
        // "上传的图片仅支持png或jpg格式",Toast.LENGTH_SHORT).show();
    }
    return null;
    }

    /**
     *
     * @author xt 重写webchromeclient
     * @date 2016年5月12日
     * @param
     * @return void
     *
     */
    protected class myWebChromeClient extends WebChromeClient {
    // For Android 3.0+
    public void openFileChooser(ValueCallback<Uri> uploadMsg,
        String acceptType) {
        if (mUploadMessage != null)
        return;
        mUploadMessage = uploadMsg;
        showImagePickDialog();
    }

    // For Android < 3.0
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        if (mUploadMessage != null)
        return;
        mUploadMessage = uploadMsg;
        showImagePickDialog();
    }

    // For Android 4.1
    public void openFileChooser(ValueCallback<Uri> uploadMsg,
        String acceptType, String capture) {
        if (mUploadMessage != null)
        return;
        mUploadMessage = uploadMsg;
        showImagePickDialog();
    }
    }

    public static void updateUrl() {
    webView.reload();
    }

    public String setloadUrl() {
    String url = ApiConstant.BASE_HTML + "control/control.html";
    return url;
    }

    public class WebUtils {
    private Context context;

    public WebUtils() {
    }

    public WebUtils(Context context) {
        this.context = context;
    }

    /**
     * 关闭网页 cjh 2015年12月20日
     */
    public void finishHtml() {
        ((Activity) context).finish();
    }

    /**
     * 需要传workId,serviceSerialId,standardServiceName cjh 2015年12月20日
     *
     * @return
     */
    public String ThreeParams() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("workId", PreferenceUtils.getWorkId());
        map.put("serviceSerialId", PreferenceUtils.getSerciceserialId());
        map.put("standardServiceName", PreferenceUtils.getStandarName());
        return GsonUtils.get().objectToJson(map);
    }

    /**
     * 传递 workId cjh 2015年12月20日
     *
     * @param workid
     * @return
     */
    public String WorkIdParams() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("workId", PreferenceUtils.getWorkId());
        return GsonUtils.get().objectToJson(map);
    }

    /**
     * 需要传workId serviceSerialId cjh 2015年12月20日
     *
     * @return
     */
    public String serviceSerialIdParams() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("workId", PreferenceUtils.getWorkId());
        map.put("serviceSerialId", PreferenceUtils.getSerciceserialId());
        return GsonUtils.get().objectToJson(map);
    }

    /**
     * 创建订单成功之后跳转到主页 cjh 2015年12月23日
     */
    public void CreateOrderSucc() {
        Intent intent = new Intent(context, MainActivity.class);
        ((Activity) context).startActivity(intent);
        ((Activity) context).finish();

    }

    /**
     * 登陆之后的信息 cjh 2016年1月12日
     *
     * @return
     */
    public String LoginInfo() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("storeId", PreferenceUtils.getStoreId());
        map.put("userId", PreferenceUtils.getUserId());
        map.put("phone", PreferenceUtils.getPhone());
        return GsonUtils.get().objectToJson(map);
    }

    /**
     * 显示网页toast弹窗 cjh 2016年2月2日
     *
     * @param message
     */
    public void showMessage(final String message) {
        ((Activity) context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
        });

    }

    }

    /**
     * @auther xt 2016年5月11日 得到根Fragment
     *
     * @return
     */
    private Fragment getRootFragment() {
    Fragment fragment = getParentFragment();
    while (fragment.getParentFragment() != null) {
        fragment = fragment.getParentFragment();
    }
    return fragment;

    }

    /**
     *
     * @copy xt Compress image by pixel, this will modify image width/height.
     *       Used to get thumbnail
     *
     * @param imgPath
     *            image path
     * @param pixelW
     *            target pixel of width
     * @param pixelH
     *            target pixel of height
     * @return
     */
    public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
    newOpts.inJustDecodeBounds = true;
    newOpts.inPreferredConfig = Config.RGB_565;
    // Get bitmap info, but notice that bitmap is null now
    Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    // 想要缩放的目标尺寸
    float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
    float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1;// be=1表示不缩放
    if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
        be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
        be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0)
        be = 1;
    newOpts.inSampleSize = 1;// 设置缩放比例
    // 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
    bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    // 压缩好比例大小后再进行质量压缩
    // return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
    return bitmap;
    }

    /**
     * @auther xt 2016年5月11日 bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

    String result = null;
    ByteArrayOutputStream baos = null;
    try {
        if (bitmap != null) {
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        baos.flush();
        baos.close();

        byte[] bitmapBytes = baos.toByteArray();
        result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
        if (baos != null) {
            baos.flush();
            baos.close();
        }
        } catch (IOException e) {
        e.printStackTrace();
        }
    }
    return result;
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值