The best place to call setPreviewDisplay()
is in surfaceChanged() If the surface is just created, surfaceChanged will be called at least once and you can startPreview()
and setPreviewDisplay there. If the surface changes and the preview already starts, you can stopPreview/setPreviewDisplay/startPreview
there. Even if your app does not change the size of the surface, the framework may still unexpectedly call surfaceChanged()
when the app starts or exits due to orientation changes. So your app really needs to handle surfaceChanged properly. You can trace the source code of camera application in Android for reference.
The code snippet in another answer works if surfaceChanged()
is only called once in the app lifecycle.