SurfaceView相机预览Activity中权限请求与相机初始化时机咨询
Great question! Let's break this down clearly for your SurfaceView camera preview Activity:
Where to Request Camera & Location Permissions?
Best choice:
onResume()
Android runtime permissions can be revoked by the user at any time—even while your app is in the background. Placing your permission check/request inonResume()ensures that every time your Activity comes to the foreground, you verify if you still hold the required permissions (CAMERA and eitherACCESS_FINE_LOCATIONorACCESS_COARSE_LOCATION). This prevents scenarios where the user denied permissions after your app launched, leading to silent camera initialization failures later.onCreate()is okay as a starting point, but not enough
You can trigger the initial permission request inonCreate(), but you must still recheck permissions inonResume(). Relying solely ononCreate()leaves your app in a broken state if the user revokes permissions and returns to your Activity.Never use
onSurfaceCreated()
The SurfaceView'sonSurfaceCreated()callback can fire before permissions are granted. Trying to request permissions here creates a race condition: your camera initialization will fail because permissions aren't ready, and you might not get a chance to prompt the user until the next Surface creation event.
Where to Initialize the Camera?
Ideal spot:
onSurfaceCreated()(after confirming permissions)
Once you've confirmed all required permissions are granted, you should initialize the camera only after the Surface is fully ready. TheonSurfaceCreated(SurfaceHolder holder)callback signals that the Surface is available, making it the perfect time to:- Open the camera instance (use
Camera.open()for the legacy Camera API, orCameraManager.openCamera()for Camera2/CameraX) - Configure camera parameters (preview size, focus mode, flash settings, etc.)
- Attach the preview to the SurfaceHolder (
camera.setPreviewDisplay(holder)for legacy API) - Start the camera preview (
camera.startPreview())
- Open the camera instance (use
Alternative: Post-permission success + Surface validity check
If you handle permissions inonResume(), once the user grants them, you can check if the Surface is already valid viasurfaceHolder.getSurface().isValid(). If it is, initialize the camera immediately; if not, wait for theonSurfaceCreated()callback to fire.Avoid
onCreate()oronResume()directly
The Surface isn't guaranteed to be ready whenonCreate()oronResume()executes. Trying to initialize the camera here will result in errors because there's no valid Surface to attach the preview to.
内容的提问来源于stack exchange,提问作者Reynaldo Napitupulu

