Android Camera:onActivityResult中的意图始终为null

时间:2017-03-21 05:51:28

标签: android android-intent android-camera

我想获取相机拍摄的照片,但是onActivityResult的意图总是为空,我尝试了几种方法,但它们没有用。这是我使用相机的代码:

private static final int REQUEST_FROM_CAMERA = 37;

public void takePhotoByCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = new File(Environment.getExternalStorageDirectory(),
          "nameOfFile" + String.valueOf(System.currentTimeMillis()) + ".jpg");
    Const.uri = Uri.fromFile(file);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Const.uri);
    intent.putExtra("return data", true);
    ((UploadLicenseActivity) mContext).startActivityForResult(intent, REQUEST_FROM_CAMERA);
}

我提供了MediaStore.EXTRA_OUTPUT并测试uri不为空。

onActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (data == null)
            Log.e("data", "data is null");
        else if (data.getData() == null)
            Log.e("data.getData", "data.getData is null");

        if (requestCode == REQUEST_FROM_CAMERA && null != data && null != data.getData()) {
            if (null != Const.uri) {
                uploadLicensePresenter.startCropActivity(Const.uri);
            } else {
                Toast.makeText(this, "Cannot retrieve selected image.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

logcat:

03-21 13:45:49.705 16424-16424 / com.ssl.pdpatrol E / data:data is null

为什么数据为空,我该如何解决?

2 个答案:

答案 0 :(得分:0)

试试这个:

private int REQUEST_TAKE_PHOTO = 1;
private Uri camera_FileUri;
Bitmap bitMapThumbnail;

//图片点击监听器

if (Build.VERSION.SDK_INT >= 23) {
                // Marshmallow+
                if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
                    requestPermission();
                } else {
                    chooseimage();
                }
            } else {
                chooseimage();
            }



  private void chooseimage() {\

 takePicture();
 }


private void takePicture() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    camera_FileUri = getOutputMediaFileUri(1);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
    // start the image capture Intent
    startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}

/ **      *创建文件uri来存储图像/视频      * /

   public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
   }

/ **      *返回图像/视频      * /

  private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == 1) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
   }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", camera_FileUri);
   }

//要求预先

  private boolean checkAccessFineLocationPermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

   private boolean checkAccessCoarseLocationPermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
  }

   private boolean checkWriteExternalStoragePermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
     }
  }

  private void requestPermission() {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
  }

  @Override
   public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                chooseimage();
            } else {
                finish();
            }
            break;
    }
     }


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_TAKE_PHOTO) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 8;

                final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
                Bitmap thumbnail = bitmap;
                final String picturePath = camera_FileUri.getPath();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                File curFile = new File(picturePath);
                try {
                    ExifInterface exif = new ExifInterface(curFile.getPath());
                    int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                    int rotationInDegrees = exifToDegrees(rotation);

                    Matrix matrix = new Matrix();
                    if (rotation != 0f) {
                        matrix.preRotate(rotationInDegrees);
                    }
                    thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
                } catch (IOException ex) {
                    Log.e("TAG", "Failed to get Exif data", ex);
                }

                thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);


                //------------Code to update----------
                bitMapThumbnail = thumbnail;
                profile_pic.setImageBitmap(thumbnail);



            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        }

答案 1 :(得分:-1)

你可以试试这个

if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK)
{
Bundle extras2 = data.getExtras();
 if (extras2 != null) {
                    // do your stuff here
                     } 
                   else {
                  // handle this case as well if data.getExtras() is null
                    Uri selectedImage = data.getData();
                   }
}

希望它可以帮到你