SoFunction
Updated on 2025-03-11

Android development realizes small screen recording function

In recent development, we need to implement the screen recording function, check relevant information, and find that we can call the MediaProjectionManager API to implement the screen recording function:

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;


public class RecordScreenActivity extends Activity {

  private boolean isRecord = false;
  private int mScreenWidth;
  private int mScreenHeight;
  private int mScreenDensity;
  private int REQUEST_CODE_PERMISSION_STORAGE = 100;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    requestPermission();
    getScreenBaseInfo();
    startScreenRecord();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    (requestCode, resultCode, data);
    if (requestCode == 1000) {
      if (resultCode == RESULT_OK) {
        //Get screen recording permission, start Service for recording        Intent intent = new Intent(this, );
        ("resultCode", resultCode);
        ("resultData", data);
        ("mScreenWidth", mScreenWidth);
        ("mScreenHeight", mScreenHeight);
        ("mScreenDensity", mScreenDensity);
        startService(intent);
        finish();
      }
    }
  }

  //start screen record
  private void startScreenRecord() {
    //Manages the retrieval of certain types of MediaProjection tokens.
    MediaProjectionManager mediaProjectionManager =
        (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    //Returns an Intent that must passed to startActivityForResult() in order to start screen capture.
    Intent permissionIntent = ();
    startActivityForResult(permissionIntent, 1000);
  }

  /**
    * Get basic screen information
    */
  private void getScreenBaseInfo() {
    //A structure describing general information about a display, such as its size, density, and font scaling.
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    mScreenWidth = ;
    mScreenHeight = ;
    mScreenDensity = ;
  }


  @Override
  protected void onDestroy() {
    ();
  }

  private void requestPermission() {
    if (.SDK_INT >= 23) {
      String[] permissions = {
          .READ_EXTERNAL_STORAGE,
          .WRITE_EXTERNAL_STORAGE,
          .RECORD_AUDIO,
          
      };

      for (String str : permissions) {
        if ((str) != PackageManager.PERMISSION_GRANTED) {
          (permissions, REQUEST_CODE_PERMISSION_STORAGE);
          return;
        }
      }
    }
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults) {
    (requestCode, permissions, grantResults);
    if(requestCode==REQUEST_CODE_PERMISSION_STORAGE){
      startScreenRecord();
    }
  }
}

Related recording work is performed in the service

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

/**
 * Created by dzjin on 2018/1/9.
 */
 
public class ScreenRecordService extends Service {
 
  private int resultCode;
  private Intent resultData=null;
 
  private MediaProjection mediaProjection=null;
  private MediaRecorder mediaRecorder=null;
  private VirtualDisplay virtualDisplay=null;
 
  private int mScreenWidth;
  private int mScreenHeight;
  private int mScreenDensity;
 
  private Context context=null;
 
  @Override
  public void onCreate() {
    ();
  }
 
  /**
   * Called by the system every time a client explicitly starts the service by calling startService(Intent),
   * providing the arguments it supplied and a unique integer token representing the start request.
   * Do not call this method directly.
   * @param intent
   * @param flags
   * @param startId
   * @return
   */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
 
    try{
      resultCode=("resultCode",-1);
      resultData=("resultData");
      mScreenWidth=("mScreenWidth",0);
      mScreenHeight=("mScreenHeight",0);
      mScreenDensity=("mScreenDensity",0);
 
      mediaProjection=createMediaProjection();
      mediaRecorder=createMediaRecorder();
      virtualDisplay=createVirtualDisplay();
      ();
    }catch (Exception e) {
      ();
    }
    /**
     * START_NOT_STICKY:
     * Constant to return from onStartCommand(Intent, int, int): if this service's process is
     * killed while it is started (after returning from onStartCommand(Intent, int, int)),
     * and there are no new start intents to deliver to it, then take the service out of the
     * started state and don't recreate until a future explicit call to (Intent).
     * The service will not receive a onStartCommand(Intent, int, int) call with a null Intent
     * because it will not be re-started if there are no pending Intents to deliver.
     */
    return Service.START_NOT_STICKY;
  }
 
  //createMediaProjection
  public MediaProjection createMediaProjection(){
    /**
     * Use with getSystemService(Class) to retrieve a MediaProjectionManager instance for
     * managing media projection sessions.
     */
    return ((MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE))
        .getMediaProjection(resultCode,resultData);
    /**
     * Retrieve the MediaProjection obtained from a succesful screen capture request.
     * Will be null if the result from the startActivityForResult() is anything other than RESULT_OK.
     */
  }
 
  private MediaRecorder createMediaRecorder(){
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    String filePathName= ()+"/"+(new Date())+".mp4";
    //Used to record audio and video. The recording control is based on a simple state machine.
    MediaRecorder mediaRecorder=new MediaRecorder();
    //Set the video source to be used for recording.
    ();
    //Set the format of the output produced during recording.
    //3GPP media file format
    (.THREE_GPP);
    //Sets the video encoding bit rate for recording.
    //param:the video encoding bit rate in bits per second.
    (5*mScreenWidth*mScreenHeight);
    //Sets the video encoder to be used for recording.
    (.H264);
    //Sets the width and height of the video to be captured.
    (mScreenWidth,mScreenHeight);
    //Sets the frame rate of the video to be captured.
    (60);
    try{
      //Pass in the file object to be written.
      (filePathName);
      //Prepares the recorder to begin capturing and encoding data.
      ();
    }catch (Exception e){
      ();
    }
    return mediaRecorder;
  }
 
  private VirtualDisplay createVirtualDisplay(){
    /**
     * name String: The name of the virtual display, must be  value must never be null.
     width int: The width of the virtual display in pixels. Must be greater than 0.
     height int: The height of the virtual display in pixels. Must be greater than 0.
     dpi int: The density of the virtual display in dpi. Must be greater than 0.
     flags int: A combination of virtual display flags. See DisplayManager for the full list of flags.
     surface Surface: The surface to which the content of the virtual display should be rendered, or null if there is none initially.
     callback : Callback to call when the virtual display's state changes, or null if none.
     handler Handler: The Handler on which the callback should be invoked, or null if the callback should be invoked on the calling thread's main Looper.
     */
    /**
     * DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR
     * Virtual display flag: Allows content to be mirrored on private displays when no content is being shown.
     */
    return ("mediaProjection",mScreenWidth,mScreenHeight,mScreenDensity,
        DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,(),null,null);
  }
 
  @Override
  public void onDestroy() {
    ();
    if(virtualDisplay!=null){
      ();
      virtualDisplay=null;
    }
    if(mediaRecorder!=null){
      ();
      mediaRecorder=null;
    }
    if(mediaProjection!=null){
      ();
      mediaProjection=null;
    }
  }
 
  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}

This is how the screen recording function is implemented. If there is anything wrong, please leave a message to discuss.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.