Android 如何实现App在后台录屏

1,198 阅读1分钟

在 Android 中实现 App 在后台录屏主要需要使用到 MediaProjection API。

MediaProjection API 是 Android 5.0(API Level 21)引入的新特性,用于捕获屏幕内容并输出到文件或流中。

下面是一个简单的示例代码,演示如何使用 MediaProjection API 在后台录屏:

  1. 定义一个 Service 用来启动和管理录屏功能:
public class RecordService extends Service {
    private MediaRecorder mMediaRecorder;
​
    @Override
    public void onCreate() {
        super.onCreate();
        createMediaRecord();
    }
​
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
​
    private void createMediaRecord() {
        mMediaRecorder = new MediaRecorder();
​
        int width = Resources.getSystem().getDisplayMetrics().widthPixels;
        int height = Resources.getSystem().getDisplayMetrics().heightPixels;
​
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent permissionIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(permissionIntent, 1);
    }
​
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            MediaProjection mediaProjection = ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE))
                    .getMediaProjection(resultCode, data);
​
            VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("ScreenCapture",
                    width, height, getResources().getDisplayMetrics().densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
                    mMediaRecorder.getSurface(), null, null);
​
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setOutputFile(getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                    + "/" + System.currentTimeMillis() + ".mp4");
            mMediaRecorder.setVideoSize(width, height);
            mMediaRecorder.setVideoFrameRate(30);
​
            try {
                mMediaRecorder.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
​
            mediaProjection.registerCallback(new MediaProjection.Callback() {
                @Override
                public void onStop() {
                    super.onStop();
                    stopRecording();
                }
            }, null);
​
            mMediaRecorder.start();
        }
    }
​
    private void stopRecording() {
        mMediaRecorder.stop();
        mMediaRecorder.release();
        mMediaRecorder = null;
        Toast.makeText(this, "录制完成", Toast.LENGTH_SHORT).show();
​
        stopSelf();
    }
}
​
  1. 在 AndroidManifest.xml 文件中注册该 Service:
<application>
    <service android:name="com.example.RecordService"/>
</application>
  1. 在 App 中启动该 Service,即可在后台进行录屏:
Intent intent = new Intent(this, RecordService.class);
startService(intent);

需要注意的是:在 Android 10 及以上版本中,需要为 App 授予「录制屏幕」权限才能正常使用 MediaProjection API,否则会出现崩溃等异常。