我想建立一个应用程序,立即运行相机,拍照,然后用图片做事情。 我使用这两种方法拍照并将其保存到设备中:
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
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
Toast.makeText(this, "Failed to save to picture", Toast.LENGTH_LONG).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
String mCurrentPhotoPath;
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 = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
这是我的onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
}
我想在应用程序启动时立即启动相机。 我该怎么办?
答案 0 :(得分:2)
不要将你的方法放在onCreate
中:如果活动永远不会被破坏,它可能不会被调用(确实经常发生)。
这样就可以了。
@Override
protected void onResume() {
super.onResume();
dispatchTakePictureIntent();
}
更新:由于没有任何反应,我建议您按照以下步骤调试问题:
记录方法的调用,以了解它是否被调用:
private void dispatchTakePictureIntent() {
Log.d("CameraApp", "dispatchTakePictureIntent was called");
// ...
}
记录可能的问题,而不是忽略" elses"子句:
private void dispatchTakePictureIntent() {
// ...
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// ...
if (photoFile != null) {
// ...
} else {
Log.e("CameraApp", "photoFile was null");
}
} else {
Log.e("CameraApp", "No activity available to call the intent");
}
}
通过这种方式,您至少可以检测到没有发生任何事情的原因:
如果您从未看到" dispatchTakePictureIntent被调用",则onResume方法存在问题,因为dispatchTakePictureIntent实际上从未被调用
如果在Logcat中打印了其他两个日志,那么您的方法中的意图和 中的代码就会出现问题。