In this lesson you will look at the code of the application that records video from your device screen with sound. To Android 5.0 the app to record video from the screen of mobile devices required root access and does not guarantee the normal operation of devices from different manufacturers. That all changed in API 21 version. There is a class MediaProjection, which provides access to video recording from the screen or sound.

Let’s look at the application code to record video from the screen of the device.

The screen layout contains a single button to start and stop recording.

Let’s move on to the code. In the main package we see three classes – class RecordApplication, the class MainActivity and the class RecordService.

Consider a class RecordApplication. The call happens in the manifest in the application section in the line android:name=.

Class RecordApplication inherited from the Application class. According to the documentation, the Application class or its successor is initialized before any other class that creates the application process.

This call to the startService method which runs the service RecordService when you start the application.

Class RecordService inherited from the Service class. About what services, details can be found from the video tutorials on our channel, starting with lesson 92.

In a nutshell, the service is a kind of task that works in background and does not use the UI. Because we need to record everything that happens on the screen no matter what app is running, so we will use the service.

Here the declared variables of classes:

MediaProjection is a token that grants the app the ability to capture screen contents and/or record system audio.

MediaRecorder class, which is used to record audio and video.

VirtualDisplay Is a virtual screen, the contents of which is rendered in the Surface, which we pass to the method createVirtualDisplay.

On what Surface are we talking lesson 132.

In a nutshell, is a component that displays an image.

Declare some more variables: a Boolean running, which will assign true to the recording process.

Further parameters of the virtual screen, the resolution is set, and the density is not yet specified.

Next comes IBinder onBind method, which allows the app to connect to the service and interact with it using the returned object RecordBinder. Read more in lesson 97

Now the lifecycle methods of a service.

OnStartCommand method is triggered at the start of the service by startService method, which is invoked in the class RecordApplication. It returns START_STICKY – this means the service will be restarted if killed by the system.

In the onCreate method? which is called at the beginning of the service, create a separate thread serviceThread using the HandlerThread class. This is a helper class for starting a new thread that has a looper that can be used to create handler classes. Input pass an arbitrary stream name and flag THREAD_PRIORITY_BACKGROUND – Standard priority background threads.

Next, we start the flow, reset the value of the variable running and create a mediaRecorder.

In the onDestroy method that is called when you stop a service, simply call the superclass method.

SetMediaProject method will be called in the MainActivity and pass the object mediaProjection.

Further, the getter for the variable running.

Method setConfig sets the parameters of the virtual screen.

In the method startRecord check if the object mediaProjection does not exist and the variable running is set to true, return false.

Call here methods initRecorder and createVirtualDisplay, which we consider later, we start recording call mediaRecorder.start(); assign a variable running = true; and return true.

StopRecord method performs the reverse operation, stops the recording and restarts the mediaRecorder to the idle state. Exempt virtualDisplay and stop mediaProjection.

Now createVirtualDisplay method that is invoked above in the method startRecord. Here, you create a virtual screen through the method mediaProjection.createVirtualDisplay, which takes an arbitrary display name, its parameters, the flag VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, which reflects the contents of a private display if the content is not displayed, and Surface.

Now initRecorder in a method that is invoked above in the method startRecord work with the mediaRecorder object.

The method setAudioSource sets the audio source used for recording.

setVideoSource specifies the video source to be used for recording.

setOutputFormat sets the format of the received record file.

setOutputFile sets the destination location and file name of the recording.

setVideoSize sets the size of the video.

setVideoEncoder determines the video encoder.

setAudioEncoder specifies the audio encoder.

setVideoEncodingBitRate sets the recording rate of the recording file, here hardcoded a constant value equal to 5 Mbps.

setVideoFrameRate sets the frame rate, 30 frames per second.

The prepare() method prepares the mediaRecorder for recording and coding data. Execute it in a try…catch block with the IOException error trapping.

Further, in the method getsaveDirectory specify the path to save record file and show a toast about this user.

Below here create an inner class RecordBinder, this is the binder for communication and interaction with the service application.

In the class _REQUEST_CODE declared constants with arbitrary values. These constants are used in intents and permissions requests to distinguish from each other come results. Read more about this, see lesson 30

Next, declare variables, classes MediaProjectionManager – Manages the retrieval of certain types of tokens MediaProjection.

MediaProjection you already know is a token that grants the app the ability to capture screen contents and/or record system audio.

Also declare an instance of our service RecordService and normal button.

In the onCreate method get the instance MediaProjectionManager session control display of media data.

Create a button, by default inactive, and the listener for her.

The onClick method for the button will call a method recordService.stopRecord, in the case that the recording is going. Otherwise, create an intent with projectionManager.createScreenCaptureIntent() and send it by the method startActivityForResult.

Next come requests permission to write to the device memory and on the recording itself.

Still here we create another intent to start the service and pass it to the method bindService, which binds the service to the application, and if the service is not running, starts it first.

In the method onDestroy untied service.

OnActivityResult method gets the result of calling the method startActivityForResult, where we send captureIntent and RECORD_REQUEST_CODE.

If the query is successful, create object MediaProjection derived from the successful query screen capture. It will be NULL if the result from the startActivityForResult() is not RESULT_OK.

The called method recordService.startRecord(); and change the button text to “Stop recording”

OnRequestPermissionsResult method is the callback for the result of the permission request. This method is invoked for each method call requestPermissions. It is possible that the process permission request from the user was interrupted. In this case you will get an empty permissions and arrays, which should be treated as a cancellation.

Next, it creates an instance of the ServiceConnection interface implementation methods onServiceConnected and onServiceDisconnected. Interface is used to monitor the status of the service.

The second method is leave blank, and in the first onServiceConnected method, which is called whenever a connection application to the service through a binder, create a class object DisplayMetrics, which is used to determine the actual parameters of the device screen resolution and density.

Get instance recordService and through his method setConfig set the parameters of the virtual screen, passing the obtained values.

Here make active button and change the text on it.

Run the application and enjoy his work.

6 thoughts on “How to create a screen recording application for Android

  1. Не могу понять:
    HandlerThread serviceThread = new HandlerThread("service_thread",

    Зачем? Можете объяснить?

Leave a Reply