当我们从相机或图库获取照片时,通常会使用Android的Intent功能来启动相应的应用程序。在ActivityResult回调中,我们将获得一个包含所选图像路径的Intent对象,以便我们可以使用该路径加载并显示相应图像。但是,有时在调用OnActivityResult时会出现崩溃的问题。
这可能是由于在使用相机或图库应用程序时,我们没有正确处理ActivityResult回调。我们需要确保在启动相机/图库时,在onCreate方法中注册我们的ActivityResultHandler代码,以确保在照片捕获完成后正确地读取并使用该图像。以下是一个示例:
public class MainActivity extends AppCompatActivity {
private Button btnCamera;
private ImageView imgView;
private Uri fileUri;
String imagePath;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int SELECT_PICTURE = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCamera = (Button) findViewById(R.id.btnCamera);
imgView = (ImageView) findViewById(R.id.imgView);
// Register onActivityResult handlers
startActivityForResult(new Intent(this, MainActivity.class), SELECT_PICTURE);
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
imagePath = getRealPathFromURI(fileUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
imgView.setImageBitmap(bitmap);
}
else if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap =