private static final int REQUEST_CODE_CAMERA = 0;
private Uri photoUri;
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Button Button = (Button) findViewById(R.id.button);
Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissionOrTakePhoto();
}
});
}
private final ActivityResultLauncher<String> permissionResult = registerForActivityResult(
new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
@Override
public void onActivityResult(Boolean isGranted) {
photoUri = takePhoto();
}
}
);
private final ActivityResultLauncher<Uri> takeImageResult = registerForActivityResult(
new ActivityResultContracts.TakePicture(), new ActivityResultCallback<Boolean>() {
@Override
public void onActivityResult(Boolean isSuccess) {
if (!isSuccess) return;
loadImage(photoUri);
}
}
);
private Uri createPhotoUri() throws IOException {
return FileProvider.getUriForFile(this,
"com.myproject.fileprovider",
createImageFile()
);
}
private File createImageFile() throws IOException {
// Create an image file name
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
}
private boolean cameraPermissionGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
}
private void requestCameraPermission() {
permissionResult.launch(Manifest.permission.CAMERA);
}
private void requestPermissionOrTakePhoto() {
if (!cameraPermissionGranted()) {
requestCameraPermission();
return;
}
photoUri = takePhoto();
}
private Uri takePhoto() {
try {
Uri photoUri = createPhotoUri();
takeImageResult.launch(photoUri);
return photoUri;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void loadImage(Uri uri) {
ImageView imageView = findViewById(R.id.imageView);
Glide.with(this)
.load(uri)
.into(imageView);
}
답변주신건 프레그먼트여서 액티비티로 옮겨서 작업했습니다.