下面列出了怎么用android.media.projection.MediaProjectionManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCreate() {
super.onCreate();
LogUtil.d(TAG, "onCreate");
results = new ArrayList<>();
createView();
mMediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mNotifications = new Notifications(getApplicationContext());
mHandler = new Handler();
injectorService = LauncherApplication.getInstance().findServiceByName(InjectorService.class.getName());
injectorService.register(this);
eventService = LauncherApplication.getInstance().findServiceByName(EventService.class.getName());
eventService.startTrackTouch();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_config);
initViews();
mMediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(MEDIA_PROJECTION_SERVICE);
VideoUtils.findEncodersByTypeAsync(ScreenRecorder.VIDEO_AVC, new VideoUtils.Callback() {
@Override
public void onResult(MediaCodecInfo[] infos) {
logCodecInfos(infos, ScreenRecorder.VIDEO_AVC);
mAvcCodecInfo = infos;
SpinnerAdapter codecsAdapter = createCodecsAdapter(mAvcCodecInfo);
mVideoCodec.setAdapter(codecsAdapter);
restoreSelections(mVideoCodec, mVideoResolution, mVideoFrameRate, mVideoBitrate);
}
});
}
@Override
// TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
@SuppressWarnings("NoSynchronizedMethodCheck")
public synchronized void initialize(final SurfaceTextureHelper surfaceTextureHelper,
final Context applicationContext, final CapturerObserver capturerObserver) {
checkNotDisposed();
if (capturerObserver == null) {
throw new RuntimeException("capturerObserver not set.");
}
this.capturerObserver = capturerObserver;
if (surfaceTextureHelper == null) {
throw new RuntimeException("surfaceTextureHelper not set.");
}
this.surfaceTextureHelper = surfaceTextureHelper;
mediaProjectionManager = (MediaProjectionManager) applicationContext.getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
}
@Override // Binder call
public int applyVirtualDisplayFlags(int flags) {
if (mType == MediaProjectionManager.TYPE_SCREEN_CAPTURE) {
flags &= ~DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
flags |= DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR
| DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION;
return flags;
} else if (mType == MediaProjectionManager.TYPE_MIRRORING) {
flags &= ~(DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR);
flags |= DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY |
DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION;
return flags;
} else if (mType == MediaProjectionManager.TYPE_PRESENTATION) {
flags &= ~DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
flags |= DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION |
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR;
return flags;
} else {
throw new RuntimeException("Unknown MediaProjection type");
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
createNotificationChannel();
//Android Q 存在兼容性问题
MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(Activity.RESULT_OK, (Intent) intent.getParcelableExtra("data"));
ColorPickManager.getInstance().setMediaProjection(mediaProjection);
if (ColorPickManager.getInstance().getColorPickerDokitView() != null) {
ColorPickManager.getInstance().getColorPickerDokitView().onScreenServiceReady();
}
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void createVirtualEnvironment() {
dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
strDate = dateFormat.format(new java.util.Date());
pathImage = Environment.getExternalStorageDirectory().getPath() + "/Pictures/";
nameImage = pathImage + strDate + ".png";
mMediaProjectionManager1 = (MediaProjectionManager) activity.getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mWindowManager1 = (WindowManager) activity.getApplication().getSystemService(Context.WINDOW_SERVICE);
windowWidth = ViewUtil.getScreenWidth(activity);
windowHeight = ViewUtil.getSceenHeight(activity);
metrics = new DisplayMetrics();
mWindowManager1.getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mImageReader = ImageReader.newInstance(windowWidth, windowHeight, 0x1, 2); //ImageFormat.RGB_565
LogUtil.d(TAG, "prepared the virtual environment");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mBtnCapture.setOnClickListener(this);
mBtnRecordScreen.setOnClickListener(this);
mBtnRecordByCodec.setOnClickListener(this);
mBtnRecordCamera.setOnClickListener(this);
mBtnScanQR.setOnClickListener(this);
mBtnRtsp.setOnClickListener(this);
mBtnSocket.setOnClickListener(this);
mProjectionManager = (MediaProjectionManager) getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
}
public void requestScreenShot() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mMediaProjectionManager = (MediaProjectionManager) this.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
try {
startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
}catch (Exception ex){
if (onSavedListener != null) {
onSavedListener.onFinish(false);
}
}
}
else
{
Environment.toast(this, "系统版本过低,无法使用截屏功能。");
if (onSavedListener != null) {
onSavedListener.onFinish(false);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMediaProjectionManager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
ImageView iv = findViewById(R.id.power_toggle);
iv.setOnClickListener(this);
iv.setOnFocusChangeListener(this);
iv.setFocusable(true);
iv.requestFocus();
setImageViews(mRecorderRunning, false);
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER));
checkForInstance();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v) {
middleBtn.setEnabled(false);
middleBtn.setTextColor(Color.DKGRAY);
if (middleBtn.getText().equals("ShareScreen")) {
MediaProjectionManager manager =
(MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
startActivityForResult(manager.createScreenCaptureIntent(), OWT_REQUEST_CODE);
} else {
executor.execute(() -> {
if (screenPublication != null) {
screenPublication.stop();
screenPublication = null;
}
});
middleBtn.setEnabled(true);
middleBtn.setTextColor(Color.WHITE);
middleBtn.setText(R.string.share_screen);
}
}
@Override
public synchronized void initialize(final SurfaceTextureHelper surfaceTextureHelper,
final Context applicationContext, final VideoCapturer.CapturerObserver capturerObserver) {
checkNotDisposed();
if (capturerObserver == null) {
throw new RuntimeException("capturerObserver not set.");
}
this.capturerObserver = capturerObserver;
if (surfaceTextureHelper == null) {
throw new RuntimeException("surfaceTextureHelper not set.");
}
this.surfaceTextureHelper = surfaceTextureHelper;
mediaProjectionManager = (MediaProjectionManager) applicationContext.getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
}
@CalledByNative
public boolean allocate(int width, int height) {
mWidth = width;
mHeight = height;
mMediaProjectionManager =
(MediaProjectionManager) ContextUtils.getApplicationContext().getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
if (mMediaProjectionManager == null) {
Log.e(TAG, "mMediaProjectionManager is null");
return false;
}
WindowManager windowManager =
(WindowManager) ContextUtils.getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
mDisplay = windowManager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
mDisplay.getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
return true;
}
RecordingSession(Context context, Listener listener, int resultCode, Intent data,
Analytics analytics, Provider<Boolean> showCountDown, Provider<Integer> videoSizePercentage) {
this.context = context;
this.listener = listener;
this.resultCode = resultCode;
this.data = data;
this.analytics = analytics;
this.showCountDown = showCountDown;
this.videoSizePercentage = videoSizePercentage;
File picturesDir = Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES);
outputRoot = new File(picturesDir, "Telecine");
notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
projectionManager = (MediaProjectionManager) context.getSystemService(MEDIA_PROJECTION_SERVICE);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity activity = getActivity();
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaProjectionManager = (MediaProjectionManager)
activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
}
private void requestCapturePermission() throws Exception{
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)) {
//5.0 之后才允许使用屏幕截图
mediaProjectionManager = (MediaProjectionManager) getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(),
REQUEST_MEDIA_PROJECTION);
}else {
throw new Exception("android版本低于5.0");
}
return;
}
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
LogUtil.d(TAG, "onCreate");
mMediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mNotifications = new Notifications(getApplicationContext());
}
private static String typeToString(int type) {
switch (type) {
case MediaProjectionManager.TYPE_SCREEN_CAPTURE:
return "TYPE_SCREEN_CAPTURE";
case MediaProjectionManager.TYPE_MIRRORING:
return "TYPE_MIRRORING";
case MediaProjectionManager.TYPE_PRESENTATION:
return "TYPE_PRESENTATION";
}
return Integer.toString(type);
}
public void init(Context context, Bundle bundle, ColorPickerDokitView colorPickerDokitView) throws Exception {
this.mColorPickerDokitView = colorPickerDokitView;
PackageManager packageManager = DoraemonKit.APPLICATION.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(AppUtils.getAppPackageName(), 0);
//适配Android Q
if (applicationInfo.targetSdkVersion >= 29) {
if (ColorPickManager.getInstance().getMediaProjection() != null) {
colorPickerDokitView.onScreenServiceReady();
} else {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(context, ScreenRecorderService.class);
intent.putExtra("data", bundle.getParcelable("data"));
context.startForegroundService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
mMediaProjectionManager = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mMediaProjectionManager != null) {
mMediaProjection = mMediaProjectionManager.getMediaProjection(Activity.RESULT_OK, (Intent) bundle.getParcelable("data"));
initImageRead(mMediaProjection);
}
}
}
private boolean requestCaptureScreen() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
return false;
}
MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getContext().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mediaProjectionManager == null) {
return false;
}
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), RequestCode.CAPTURE_SCREEN);
return true;
}
public void startRecorder(Activity activity) {
if (isStart || activity == null || activity.isFinishing()) {
return;
}
isStart = true;
mediaProjectionManager = (MediaProjectionManager) QPMManager.getInstance().getContext().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
Intent intent = mediaProjectionManager.createScreenCaptureIntent();
PackageManager packageManager = activity.getPackageManager();
if (packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
//存在录屏授权的Activity
activity.startActivityForResult(intent, REQUEST_CODE);
} else {
onRecorderFailed(activity);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
windowWidth = metrics.widthPixels;
windowHeight = metrics.heightPixels;
mImageReader = ImageReader.newInstance(windowWidth, windowHeight, PixelFormat.RGBA_8888, 2);
mMediaProjectionManager = (MediaProjectionManager) getActivity().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
}
/**
* Get media projection media projection.
*
* @param context the context
* @return the media projection
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected static MediaProjection getMediaProjection(Context context){
MediaProjectionManager mgr= (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if(mMediaProjection!=null){
mMediaProjection.stop();
mMediaProjection=null;
}
mMediaProjection = mgr.getMediaProjection(Activity.RESULT_OK, (Intent) screenshotPermission.clone());
return mMediaProjection;
}
private void startOCR() {
if (canOverdraw()) {
if (!isServiceRunning(OCRFloating.class)) {
mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), Constant.CODE_FOR_SCREEN_CAPTURE);
}
} else {
requestOverlayPermission();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public synchronized void init(Context appContext,
RCRTCVideoOutputStream outputStream, Intent mediaProjectionData, int width, int height) {
this.mOutputStream = outputStream;
this.mSurfaceTextureHelper = RongRTCSurfaceTextureHelper
.create("ScreenCapturer", RongRTCVideoViewManager.getInstance().getBaseContext());
this.mMediaProjectionData = mediaProjectionData;
this.mediaProjectionManager = (MediaProjectionManager)
appContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
this.mMediaProjection = mediaProjectionManager
.getMediaProjection(Activity.RESULT_OK, this.mMediaProjectionData);
this.mVirtualDisplay = createVirtualDisplay(width, height);
outputStream.setSource(new IRCRTCVideoSource() {
@Override
public void onInit(IRCVideoConsumer observer) {
videoConsumer = observer;
}
@Override
public void onStart() {
enabled = true;
}
@Override
public void onStop() {
enabled = false;
}
@Override
public void onDispose() {
videoConsumer = null;
}
});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void requestForScreenCast() {
if (!screenCastEnable) {
String toastInfo = getResources().getString(R.string.screen_cast_disabled);
Toast.makeText(this, toastInfo, Toast.LENGTH_SHORT).show();
return;
}
MediaProjectionManager manager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(manager.createScreenCaptureIntent(), SCREEN_CAPTURE_REQUEST_CODE);
}
private void startScreenCapture() {
Log.d("WOW", "start cap");
mProjectionManager = (MediaProjectionManager) getActivity().getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(mProjectionManager.createScreenCaptureIntent(),
1000);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_record_by_codec);
ButterKnife.bind(this);
mBtnRecord.setOnClickListener(this::onButtonClick);
mMediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(
MEDIA_PROJECTION_SERVICE);
}
private void initActivity() {
// assume the recorder is not running until we are notified otherwise
mRecorderRunning = false;
setContentView(R.layout.activity_main);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
mMediaProjectionManager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
ImageView iv = findViewById(R.id.power_toggle);
iv.setOnClickListener(this);
iv.setOnFocusChangeListener(this);
iv.setFocusable(true);
iv.requestFocus();
ImageButton ib = findViewById(R.id.settingsButton);
ib.setOnClickListener(this);
ib.setOnFocusChangeListener(this);
ib.setFocusable(true);
setImageViews(mRecorderRunning, false);
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(BROADCAST_FILTER));
// request an update on the running status
checkForInstance();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MediaProjectionManager manager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (manager != null) {
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
} else {
finish();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private boolean prepared() {
Preferences prefs = new Preferences(getBaseContext());
String host = prefs.getString(R.string.pref_key_host, null);
int port = prefs.getInt(R.string.pref_key_port, -1);
String priority = prefs.getString(R.string.pref_key_priority, "50");
mFrameRate = prefs.getInt(R.string.pref_key_framerate);
mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led);
mVerticalLEDCount = prefs.getInt(R.string.pref_key_y_led);
mSendAverageColor = prefs.getBoolean(R.string.pref_key_use_avg_color);
RECONNECT = prefs.getBoolean(R.string.pref_key_reconnect);
int delay = prefs.getInt(R.string.pref_key_reconnect_delay);
if (host == null || Objects.equals(host, "0.0.0.0") || Objects.equals(host, "")) {
mStartError = getResources().getString(R.string.error_empty_host);
return false;
}
if (port == -1) {
mStartError = getResources().getString(R.string.error_empty_port);
return false;
}
if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
mStartError = getResources().getString(R.string.error_invalid_led_counts);
return false;
}
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mHyperionThread = new HyperionThread(mReceiver, host, port, Integer.parseInt(priority), RECONNECT, delay);
mHyperionThread.start();
mStartError = null;
return true;
}