我正在嘗試創建和Android應用程序拍攝照片或將照片上載到服務器。我的主要目標是獲取意圖返回的照片的URI。我遵循了[1]中的步驟。 問題是,在具有Lollipop版本5.1.1的電話上,它工作正常,意圖返回照片的URI,但在具有Jelly Bean版本4.2.1的電話中,意圖返回的URI爲null 。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
您可以加入整體功能,而不是這個只有部分? – RafaelC
我添加了洞功能 – Ancuta
這可能是您的JB設備上的攝像機意圖的錯誤實施。嘗試在此設備上安裝[打開相機](https://play.google.com/store/apps/details?id=net.sourceforge.opencamera&hl=en),並檢查其行爲是否有所不同。 –