我正在创建一个相机应用程序,目前我正在其中通过捕捉快照并将其发布到ImageView中来测试设备相机是否正常工作。 问题是当我使用前置摄像头时,它工作正常,但似乎不适用于后置摄像头。代码是:
//代码以获取快照:
private void dispatchTakePictureIntent() {
//Toast.makeText(this, "Button Just Clicked", Toast.LENGTH_SHORT).show();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
Log.d("Camera Exists", "True");
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
Log.d("Uri Exists", "True");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 1);
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
intent.putExtra("key", mCurrentPhotoPath);
MainActivity.this.startActivity(intent);
}
}
}
//代码以在imageview中显示图像:
Intent intent = getIntent();
String value = intent.getStringExtra("key");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
imageView = findViewById(R.id.image);
File imgFile = new File(value);
imageView.setImageURI(Uri.fromFile(imgFile));
正如我提到的,当我使用前置摄像头时,imageview包含快照,而当我使用后置摄像头时则不包含快照。