背景
startActivityForResult(Intent,int) での画像選択コードが deprecated と言われるので、修正前後のコード例を残しておく。
コード
修正前
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private final static int RESULT_PICK_IMAGEFILE = 1000;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == RESULT_PICK_IMAGEFILE && resultCode == RESULT_OK) {
if (resultData != null) {
Uri uri = resultData.getData();
// Do something here.
}
}
}
private void onSelectImage() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, RESULT_PICK_IMAGEFILE); // deprecated!!
}
}
修正後
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ActivityResultLauncher<Intent> _launcherSelectSingleImage = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Intent resultData = result.getData();
if (resultData != null) {
Uri uri = resultData.getData();
// Do something here.
}
}
}
});
private void onSelectImage() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
Intent chooserIntent = Intent.createChooser(intent, "単一画像の選択");
_launcherSelectSingleImage.launch(chooserIntent);
}
}