如果在使用ActivityResultContracts.TakePicture()时屏幕旋转,uri将会发生丢失的问题。为了解决这个问题,可以将Uri传递给onSaveInstanceState()方法以在屏幕旋转后恢复其状态。如果不恢复状态,则无法获得拍照的实际路径。以下是解决此问题的示例代码:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
private static final String STATE_URI = "state_uri";
private Uri mUri;
private ActivityResultLauncher mStartForResult = registerForActivityResult(
new ActivityResultContracts.TakePicture(), result -> {
if (result) {
// Do something with the saved image uri
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check if there is a saved uri
if (savedInstanceState != null) {
mUri = savedInstanceState.getParcelable(STATE_URI);
}
// Capture a picture
capturePicture();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_URI, mUri);
}
private void capturePicture() {
File imageFile = createImageFile();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", imageFile);
} else {
mUri = Uri.fromFile(imageFile);
}
mStartForResult.launch(mUri);
}
private File createImageFile() {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// Save the image file in the external storage directory
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(storageDir, imageFileName + ".jpg");
}
}