如何从片段拍照

时间:2017-03-28 16:30:24

标签: android android-fragments firebase android-camera

我想从片段拍摄照片,但如果我使用关注代码 onActivityResult意图数据 返回 null 。我没有弄明白为什么 Intent数据返回null

CameraFragement.java

move_uploaded_file($_FILES['userfile']['tmp_name'],$pathname)

如果我使用此跟随代码而不是上面 takePictureIntent Intent数据返回附加内容 data.getData()返回null 。我不想用额外的东西返回数据。我不想要Bitmap数据。我需要数据Uri形式。我需要 data.getData()。以下代码以前使用过,但现在它不起作用。我总是使用Android SDK更新我的应用程序。我认为这是原因,但解决方案是什么?

private void takePictureIntent() {

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(getContext(),
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

String imagePath;

private File createImageFile() throws IOException {

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    imagePath = image.getAbsolutePath();
    return image;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)  { // this Intent data return null
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {


        Intent intent = new Intent(getActivity(), PostActivity.class);
        intent.setData(data.getData());
        startActivity(intent);

    } 
}

编辑我几乎尝试了所有内容,但 Intent数据仍然返回null 。我现在正在使用第一个代码示例的跟随代码。你可以使用它,它的工作正常。如果你有Intent数据的解决方案,请不要忘记注意我。

private void takePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}

3 个答案:

答案 0 :(得分:1)

请求代码在片段中丢失,您需要使用活动上下文:

getActivity().startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

答案 1 :(得分:1)

//捕捉图片

public void requestTakePhoto() {
 //SettingsManager.sharedInstance().TAKE_PHOTO = true;
 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
  final File photoFile;
  try {
    photoFile = createImageFile();
  }
  catch (IOException e) {
    // Error occurred while creating the File
    Log.e("ChatActivity", "Unable to create photo file", e);
    return;
  }
  // Continue only if the File was successfully created
  intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
  startActivityForResult(intent, REQ_TAKE_PHOTO);
  }
}

//保存捕获的图像

private Uri mPhotoLocation;
private File createImageFile() throws IOException {
  final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(newDate());
  final String imageFileName = timeStamp + "filename";
  final File storageDir =     Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
  final File image = File.createTempFile(imageFileName, ".jpg", storageDir);
  mPhotoLocation = Uri.fromFile(image);
  return image;
}

//处理结果

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data){

 switch (requestCode) {
  case REQ_PICK_IMAGE:
    if (resultCode == Activity.RESULT_OK && data.getData() != null) {

      Uri  uri =data.getData();

      //do your work with data

     // String filePath = getRealPathFromUri(uri);
      //if (filePath != null && !filePath.isEmpty()) {
       // Uri fileUri = Uri.parse(filePath);
        //sendImageMessage(fileUri);
      }
    }
    break;
  case REQ_TAKE_PHOTO:
    if (resultCode == Activity.RESULT_OK ) {
      //do your work with data
      String filePath = getRealPathFromUri(mPhotoLocation);
      if (filePath != null && !filePath.isEmpty()) {
        Uri fileUri = Uri.parse(filePath);
        sendImageMessage(fileUri);
      }
      mPhotoLocation = null;
    }
    break;
  case REQ_FILE_ATTACHMENT:
    if (resultCode == Activity.RESULT_OK && data.getData() != null) {
      Uri uri = data.getData();
      //String filePath = getRealPathFromUri(uri);
      //if (filePath != null && !filePath.isEmpty()) {
        //Uri fileUri = Uri.parse(filePath);
        //sendFileMessage(fileUri);
      }
    }
    break;
  default:
    super.onActivityResult(requestCode, resultCode, data);
    break;
  }
}

//获取真实路径

public String getRealPathFromUri(final Uri uri) {
// DocumentProvider
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(getActivity(), uri)) {
  // ExternalStorageProvider
   if (isExternalStorageDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    if ("primary".equalsIgnoreCase(type)) {
      return Environment.getExternalStorageDirectory() + "/" + split[1];
    }
  }
  // DownloadsProvider
  else if (isDownloadsDocument(uri)) {

    final String id = DocumentsContract.getDocumentId(uri);
    final Uri contentUri = ContentUris.withAppendedId(
      Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

    return getDataColumn(getActivity(), contentUri, null, null);
  }
  // MediaProvider
  else if (isMediaDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    Uri contentUri = null;
    if ("image".equals(type)) {
      contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
      contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if ("audio".equals(type)) {
      contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    }

    final String selection = "_id=?";
    final String[] selectionArgs = new String[]{
      split[1]
    };

    return getDataColumn(getActivity(), contentUri, selection, selectionArgs);
  }
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {

  // Return the remote address
  if (isGooglePhotosUri(uri))
    return uri.getLastPathSegment();

  return getDataColumn(getActivity(), uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
  return uri.getPath();
}

 return null;
}


private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
  column
};

try {
  cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
    null);
  if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow(column);
    return cursor.getString(index);
  }
} finally {
  if (cursor != null)
    cursor.close();
}
 return null;
 }

private boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
}


private boolean isDownloadsDocument(Uri uri) {
   return "com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

private boolean isMediaDocument(Uri uri) {
  return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

private boolean isGooglePhotosUri(Uri uri) {
   return "com.google.android.apps.photos.content".equals(uri.getAuthority());
 }

答案 2 :(得分:0)

此库可帮助您从CameraStorage获取图片,以便在ActivityFragment中查看。 它提供了非常简单的方法,

https://github.com/coomar2841/image-chooser-library