Media Projection API was introduced in Android 5(Lollipop). Using this API we can record the screen content with audio recording and can also capture the screen. A Media Projection API involves three screens of the device display. The first one is the real display, the second one is the virtual display and the third is the surface.
Prerequisite
- Android SDK v21
- <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
- <uses-permission android:name=”android.permission.RECORD_AUDIO”/>
- <uses-permission android:name=”android.permission.FOREGROUND_SERVICE”/>
Foreground permission is required for android 10 and above versions while for versions below Android 10 we can record the screen without it.
Define service in manifests file like this below:
<application> <service android:enabled="true" android:name=".ScreenCapturerService" android:foregroundServiceType="mediaProjection"> </service> </application>
Steps to record screen:
Step-1 Send a request for permission
Launching this intent will show a dialog to the user which allows them for screen recording.
MediaProjectionManager mProjectionManager (MediaProjectionManager)getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE);
Intent permissionIntent = mProjectionManager.createScreenCaptureIntent();
startActivityForResult(permissionIntent, REQUEST_CODE_CAPTURE_PERM);
Step-2 Get a call back of request for permission
Once they accept, you can use the result code and data intent returned in onActivityResult, Now we will be able to create a Media Projection.
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE_CAPTURE_PERM == requestCode) { if (resultCode == RESULT_OK) { //permission allow } else { //permission deny } } }
Step-3 Create Media Projection and create notification
MediaProjection mediaProjection = ApplicationClass.mProjectionManager.getMediaProjection(resultCode, data);
Step-4 Then we have to use Media Recorder for screen recording with audio and have to define the height and width using the Window’s DisplayMetrics so it exactly matches the screen size. Then define the path where you want to save your recorded screen video.
int displayWidth, displayHeight, mScreenDensity private void record() { MediaRecorder mediaRecorder = new MediaRecorder(); //for where recorded video save File screenRecording = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES).getAbsolutePath() + "/Screen Recorder"); if (!screenRecording.exists()) { screenRecording.mkdirs(); } String videoDir = recordedVideos.getAbsolutePath(); String timestamp; timestamp = "Screen_Recorder_Video_" + System.currentTimeMillis(); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) { File f = new File(videoDir); f.mkdir(); } filePath = videoDir + "/" + timestamp + ".mp4"; //for displaying screen size DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE); wm.getDefaultDisplay().getRealMetrics(metrics); mScreenDensity = metrics.densityDpi; displayWidth = metrics.widthPixels; displayHeight = metrics.heightPixels; mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.MIC); mediaRecorder.setVideoEncodingBitRate(8 * 1000 * 1000); mediaRecorder.setVideoFrameRate(24); mediaRecorder.setVideoSize(displayWidth, displayHeight); mediaRecorder.setOutputFile(filePath); mediaRecorder.prepare(); }
Step-5 Create virtual display
return getMediaProjection().createVirtualDisplay(“ScreenRecorderActivity”,
displayWidth, displayHeight, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder.getSurface(), null, null);
Step-6 call it by using the override oncreate method
record();
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
step -7 You can manage the Stop,Play, and Pause Screen Recording facility by using the code below
Play:
if (mediaRecorder != null) { mediaRecorder.resume(); } Pause: if (mediaRecorder != null) { mediaRecorder.pause(); }
Stop:
if (virtualDisplay != null && mediaRecorder != null) { virtualDisplay.release(); try { mediaRecorder.stop(); } catch (Exception e) { e.printStackTrace(); } mediaRecorder.reset(); if (mediaProjection != null) { mediaProjection.stop(); mediaProjection = null; } }