Android 在应用程序启动时启动摄像头
我想建立一个应用程序,立即运行相机,拍照,然后做的事情与照片。 我使用以下两种方法拍摄照片并将其保存到设备:Android 在应用程序启动时启动摄像头,android,camera,startup,oncreate,Android,Camera,Startup,Oncreate,我想建立一个应用程序,立即运行相机,拍照,然后做的事情与照片。 我使用以下两种方法拍摄照片并将其保存到设备: static final int REQUEST_TAKE_PHOTO = 1; private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camer
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);
}
我想在应用程序启动时立即启动相机。
我该怎么做呢?不要将您的方法放在
onCreate
中:如果活动从未被破坏过,则可能不会调用该方法(事实上,这种情况经常发生)。
这样就行了
@Override
protected void onResume() {
super.onResume();
dispatchTakePictureIntent();
}
更新:由于没有发生任何事情,我建议您执行以下步骤来调试问题:
private void dispatchTakePictureIntent() {
Log.d("CameraApp", "dispatchTakePictureIntent was called");
// ...
}
在onResume中调用您的拍照代码在OnCreate中设置摄像头正如您所说,我使用onResume调用此方法,但什么都没有发生。我还添加了使用相机和使用存储的权限。我怎样才能修好它?
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");
}
}