Android API 30 (Android 11) 이상부터 startActivityForResult() 및 onActivityResult()가 Deprecated 되었습니다. 대신 **Activity Result API**를 사용해야 합니다.
Activity Result API 적용startActivityForResult())java
복사편집
startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
java
복사편집
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == FILE_CHOOSER_RESULT_CODE && resultCode == RESULT_OK) {
// 결과 처리
}
}
📌 startActivityForResult()는 이제 Deprecated!
Activity Result API 적용 방식 (업데이트된 코드)registerForActivityResult()를 사용하여 ActivityResultLauncher를 등록java
복사편집
private ActivityResultLauncher<Intent> fileChooserLauncher;
// ActivityResultLauncher 초기화
private void initFileChooserLauncher() {
fileChooserLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (filePathCallback == null) return;
Uri[] results = null;
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
if (data == null || data.getData() == null) {
if (cameraPhotoPath != null) {
results = new Uri[]{Uri.parse(cameraPhotoPath)};
}
} else {
results = new Uri[]{data.getData()};
}
}
filePathCallback.onReceiveValue(results);
filePathCallback = null;
}
);
}
onShowFileChooser에서 ActivityResultLauncher 사용startActivityForResult()를 사용하지 않고 새로운 방식으로 파일 선택기 실행:
java
복사편집
@Override
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (WebViewActivity.this.filePathCallback != null) {
WebViewActivity.this.filePathCallback.onReceiveValue(null);
}
WebViewActivity.this.filePathCallback = filePathCallback;
// 카메라 촬영 Intent 생성
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
Uri photoUri = FileProvider.getUriForFile(
WebViewActivity.this,
getApplicationContext().getPackageName() + ".fileprovider",
photoFile
);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// 갤러리에서 파일 선택 Intent
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray = takePictureIntent != null ? new Intent[]{takePictureIntent} : new Intent[0];
// 파일 선택 다이얼로그 실행
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "사진 선택");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
// 새 Activity Result API 사용
fileChooserLauncher.launch(chooserIntent);
return true;
}
ActivityResultLauncher 등록initFileChooserLauncher() 메서드를 onCreate()에서 호출