当使用ActivityResultContracts.TakePicture获取图片时,如果在拍照后屏幕发生旋转,那么拍摄的照片将不会被保存。这是因为屏幕旋转会导致Activity被销毁和重建,在重建后与之前的Activity不同,可以导致丢失拍摄的照片。
要解决这个问题,可以在Activity的onSaveInstanceState方法中保存照片的URI,然后在重建Activity后恢复URI并将其用作保存照片的文件路径。以下是代码示例:
public class MainActivity extends AppCompatActivity {
private Uri photoUri;
private ActivityResultLauncher takePicture = registerForActivityResult(
new ActivityResultContracts.TakePicture(),
result -> {
if (result) {
// do something with the photo
}
}
);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
photoUri = savedInstanceState.getParcelable("photo_uri");
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("photo_uri", photoUri);
}
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoUri = getPhotoUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
takePicture.launch(intent);
}
private Uri getPhotoUri() {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "photo.jpg");
return FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQUEST_OPEN_CAMERA) {
// do something with the photo
}
}
}
在上面的代码中,我们在Activity