关于相机拍照获取图片onActivityResult返回data 为null的问题

调用相机拍摄方法

/**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isSdcardExist()) {
            Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    FileProvider.getUriForFile(getActivity(),"你的包名.fileprovider", cameraFile));
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        }
        startActivityForResult(intent, REQUEST_CODE_CAMERA);

    }

相机拍摄后的回调如下:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //xqxhx add  避免data数据为null
        if (data==null){
            return;
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                if (cameraFile != null && cameraFile.exists()) {
                    sendImageMessage(cameraFile.getAbsolutePath());
                }

此时发现 代码执行到 if(data==null)就结束了,问题为为什么拍摄相机的回调图片数据data为null

查询发现:

照相机有自己默认的存储路径,拍摄的照片将返回一个缩略图,即data里面保存的数据。

但是如果自己代码指定了保存图片的uri,data里面就不会保存数据。也就是说,调用相机时指定了uri,data就没有数据,没有指定uri,data就有数据。

但是这个规律也不是适用于所有的安卓手机,红米和三星部分型号在没有指定uri时,data依然没有数据。

由此上述If(data==null){retrun;}

看上去是做了一层保护,避免数据异常的情况发生,但是在此情况下,则不适用,去除即可继续执行下面的代码。

原文地址:https://www.cnblogs.com/xqxacm/p/9778213.html