我正在尝试创建和Android应用程序拍摄照片或将照片上传到服务器。我的主要目标是获取意图中返回的照片的URI。我按照[1]中的步骤进行操作。 问题是在带有Lollipop的手机上,版本5.1.1工作正常并且意图返回照片的URI,但是在具有Jelly Bean版本4.2.1的手机上,意图中返回的URI为空。
这是我的代码
创建视图并将听众设置为按钮
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_GET_PHOTO = 2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_page, container, false);
camera = (FloatingActionButton) view.findViewById(R.id.take_photo);
upload = (FloatingActionButton) view.findViewById(R.id.upload_photo);
photo = (ImageView) view.findViewById(R.id.photo);
camera.setOnClickListener(takePhoto);
upload.setOnClickListener(uploadPhoto);
return view;
}
拍照行动
View.OnClickListener takePhoto = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
};
从图库收听者上传
View.OnClickListener uploadPhoto = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
if (photoPickerIntent.resolveActivity(getActivity().getPackageManager()) != null) {
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_GET_PHOTO);
}
}
};
处理意图结果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_GET_PHOTO)) {
Uri imageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), imageUri);
String filePath = getPath(imageUri);
bitmap = BitmapRotator.rotateBitmap(bitmap, filePath);
photo.setImageBitmap(bitmap);
UploadPhotoController.uploadPhoto(filePath);
} catch (IOException e) {
e.printStackTrace();
} catch (PhotoNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
data.getData()为null因此我无法获取uri或图像的文件路径。
谢谢。
[1] http://developer.android.com/training/camera/photobasics.html
答案 0 :(得分:0)