Android MediaProjection 录屏方案

```bash
公众号同名
```
 

MediaProjection是Android5.0后提出的一套用于录制屏幕的API,无需root权限。与 MediaProjection协同的类有 MediaProjectionManager, MediaCodec等。

获取MediaProjection对象

申请权限

在使用 MediaPeojection相关API时,需要请求系统级录制屏幕权限,申请权限的方法如下:

//通过getSystemService获取MediaProjectionManager对象

mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);

Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();

startActivityForResult(captureIntent, REQUEST_CODE);

在 onActivityResult方法中处理回调并初始化 MediaProjection对象

MediaProjection mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);

MediaProjectionManager获取过程

通过 context.getSystemService(MEDIA_PROJECTION_SERVICE)获取 MediaProjectionManager的详细流程:

Context#getSystemSevice

public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);

ContextImpl#getSystemService

@Override

public Object getSystemService(String name) {

return SystemServiceRegistry.getSystemService(this, name);

}

SystemServiceRegistry#getSystemService

private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =

new HashMap<String, ServiceFetcher<?>>();
/**

* Statically registers a system service with the context.

* This method must be called during static initialization only.

*/

private static <T> void registerService(String serviceName, Class<T> serviceClass,

ServiceFetcher<T> serviceFetcher) {

SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);

SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);

}
registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class,

new CachedServiceFetcher<MediaProjectionManager>() {

@Override

public MediaProjectionManager createService(ContextImpl ctx) {

return new MediaProjectionManager(ctx);

}});
/**

* Gets a system service from a given context.

*/

pu
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值