```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