Android Phone Record Screen Error: failed to get surface

As long as it is recorded on the screen, it is difficult to report errors. The common causes and solutions are summarized as follows:

1. Determine the storage permission. Note that Android 10, 11, 12, etc. the storage permission policy of Android has changed. Set the output path to ensure that it is under the path with read-write permission

File file=new File(getExternalFilesDir("")+"/Ansen_");
if(!file.exists()){
    file.mkdirs();
}
//Set the video output path
mMediaRecorder.setOutputFile(file.getAbsolutePath() + "/Ansen_" + curTime + ".mp4");

2. Correctly set the size of the recording screen, here note that this size is not necessarily the screen size, through the following method is not necessarily the same as the actual resolution, such as a plus phone, originally 1920 * 1080, in fact, through the following measurement results are not, this will require developers to get through the Camera.

 //Set the video size
 mMediaRecorder.setVideoSize(ScreenUtils.getScreenWidth(this), ScreenUtils.getScreenHeight(this));

Conventional method for obtaining the size of mobile phone (not necessarily accurate, inconsistent with the recording screen):

    /**
     * Get the width of the screen px
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * Get the width of the screen px
     */
    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

To get the resolution supported by the camera, just select a group from the following.

        Camera camera = Camera.open();
        Parameters parameters = camera.getParameters();
        List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();

        for (int i = 0; i < supportedPreviewSizes.size(); i++) {
            supportedPreviewSizes.get(i).width;
            supportedPreviewSizes.get(i).height;
        }
        List<Size> supportedPictureSizes = parameters.getSupportedPictureSizes();
        for (int i = 0; i < supportedPictureSizes.size(); i++) {
            supportedPictureSizes.get(i).widt;
            supportedPictureSizes.get(i).height;
        }

3. Determine the setting sequence, which will affect

setAudioSource()

setVideoSource()

setOutputFormat()

setAudioEncoder()

setVideoEncoder()

setVideoSize()

setVideoFrameRate()

setOutputFile()

setVideoEncodingBitRate()

prepare()

start()

Read More: