import com.example.webrtcdemo.utils.UIUtils;
/**
- 录屏
*/
public class RecordScreenActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 102;
private MediaProjectionManager projectionManager;
private MediaProjection mediaProjection;
private VirtualDisplay mVirtualDisplay;
private SurfaceView mSurfaceView;
@Override
protected void onDestroy() {
super.onDestroy();
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
mVirtualDisplay = null;
if (mediaProjection != null) {
mediaProjection.stop();
mediaProjection = null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_screen);
mSurfaceView = findViewById(R.id.surface_view);
projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
Intent captureIntent = projectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = projectionManager.getMediaProjection(resultCode, data);
mVirtualDisplay = createVirtualDisplay();
}
}
/**
-
name: 是生成的VirtualDisplay实例的名称;
-
widt
h, height: 分别是生成实例的宽高,必须大于0; -
dpi: 生成实例的像素密度,必须大于0,一般都取1;
-
surface: 这个比较重要,是你生成的VirtualDisplay的载体,
-
我的理解是,VirtualDisplay的内容是一帧帧的屏幕截图(所以你看到是有宽高,像素密度等设置),
-
所以MediaProjection获取到的其实是一帧帧的图,然后通过 surface(surface你可以理解成是android的一个画布,
-
默认它会以每秒60帧来刷新,这里我们不再展开细说),来顺序播放这些图片,形成视频。
-
@return
*/
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay(“RecordScreen”,
UIUtils.getScreenWidth(this), UIUtils.getScreenHeight(this),
UIUtils.getScreenDpi(this),
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mSurfaceView.getHolder().getSurface(), null /Callbacks/, null /Handler/);
}
}
<uses-feature
android:glEsVersion=“0x00020000”
android:required=“true” />
mission.ACCESS_NETWORK_STATE" />