How do I restrict recording of youtube app package using mediaprojection api from my app? I created screencast application using mediaprojection api, it records everything from screen, I want to restrict apps like youtube, whatsapp etc. I tried using devicepolicymanager but didn’t worked. Here’s my Mediaprojection service class code, targetsdk: api 34
private String TAG = MediaProjectionService.class.getSimpleName();
private static final String RESULT_CODE = "RESULT_CODE";
private static final String DATA = "DATA";
private static final String ACTION = "ACTION";
private static final String START = "START";
private static final String STOP = "STOP";
private static final String SCREENCAST = "SCREENCAST";
private static int IMAGES_PRODUCED;
private MediaProjection mediaProjection;
private String dir;
private ImageReader imageReader;
private Handler handler;
private Display display;
private VirtualDisplay virtualDisplay;
private int density;
private int width;
private int height;
private int rotation;
private OrientationChangeCallback orientationChangeCallback;
private static boolean isStartCommand(Intent intent) {
return intent.hasExtra(RESULT_CODE) && intent.hasExtra(DATA)
&& intent.hasExtra(ACTION) && Objects.equals(intent.getStringExtra(ACTION), START);
}
private static boolean isStopCommand(Intent intent) {
return intent.hasExtra(ACTION) && Objects.equals(intent.getStringExtra(ACTION), STOP);
}
public static Intent startIntent(Context context, int resultCode, Intent data) {
Intent intent = new Intent(context, MediaProjectionService.class);
intent.putExtra(ACTION, START);
intent.putExtra(RESULT_CODE, resultCode);
intent.putExtra(DATA, data);
return intent;
}
public static Intent stopIntent(Context context) {
Intent intent = new Intent(context, MediaProjectionService.class);
intent.putExtra(ACTION, STOP);
return intent;
}
private static int getVirtualDisplay() {
return DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
}
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
@Override
public void onImageAvailable(ImageReader reader) {
FileOutputStream fos = null;
Bitmap bitmap = null;
try (Image image = imageReader.acquireLatestImage()) {
if (image != null) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
fos = new FileOutputStream(dir + "/myscreen_" + IMAGES_PRODUCED + ".png");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
IMAGES_PRODUCED++;
Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
}
private class OrientationChangeCallback extends OrientationEventListener {
OrientationChangeCallback(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
final int rotation = display.getRotation();
if (rotation != MediaProjectionService.this.rotation) {
MediaProjectionService.this.rotation = rotation;
try {
if (virtualDisplay != null) virtualDisplay.release();
if (imageReader != null) imageReader.setOnImageAvailableListener(null, null);
createVirtualDisplay();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class MediaProjectionStopCallback extends MediaProjection.Callback {
@Override
public void onStop() {
Log.e(TAG, "Media projection stopped!");
Toast.makeText(getApplicationContext(), "Media projection stopped!",Toast.LENGTH_SHORT).show();
handler.post(new Runnable() {
@Override
public void run() {
if (virtualDisplay != null) virtualDisplay.release();
if (imageReader != null) imageReader.setOnImageAvailableListener(null, null);
if (orientationChangeCallback != null) orientationChangeCallback.disable();
mediaProjection.unregisterCallback(MediaProjectionStopCallback.this);
}
});
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
File externalFilesDir = getExternalFilesDir(null);
if (externalFilesDir != null) {
dir = externalFilesDir.getAbsolutePath() + "/screenshots/";
File storeDirectory = new File(dir);
if (!storeDirectory.exists()) {
boolean success = storeDirectory.mkdirs();
if (!success) {
Log.e(TAG, "failed to create file storage directory");
stopSelf();
}
}
} else {
Log.e(TAG, "failed to create file directory");
stopSelf();
}
// start capture handling thread
new Thread() {
@Override
public void run() {
Looper.prepare();
handler = new Handler();
Looper.loop();
}
}.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isStartCommand(intent)) {
Pair<Integer, Notification> notification = NotificationUtils.getNotification(this);
startForeground(notification.first, notification.second);
// start projection
int resultCode = intent.getIntExtra(RESULT_CODE, Activity.RESULT_CANCELED);
Intent data = intent.getParcelableExtra(DATA);
startProjection(resultCode, data);
} else if (isStopCommand(intent)) {
stopProjection();
stopSelf();
} else {
stopSelf();
}
return START_NOT_STICKY;
}
private void startProjection(int resultCode, Intent data) {
MediaProjectionManager mpManager =
(MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mediaProjection == null) {
mediaProjection = mpManager.getMediaProjection(resultCode, data);
if (mediaProjection != null) {
// display metrics
density = Resources.getSystem().getDisplayMetrics().densityDpi;
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
display = windowManager.getDefaultDisplay();
createVirtualDisplay();
orientationChangeCallback = new OrientationChangeCallback(this);
if (orientationChangeCallback.canDetectOrientation()) {
orientationChangeCallback.enable();
}
mediaProjection.registerCallback(new MediaProjectionStopCallback(), handler);
}
}
}
private void stopProjection() {
if (handler != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (mediaProjection != null) {
mediaProjection.stop();
}
}
});
}
}
//recreate virtual display based on device resolution
@SuppressLint("WrongConstant")
private void createVirtualDisplay() {
width = Resources.getSystem().getDisplayMetrics().widthPixels;
height = Resources.getSystem().getDisplayMetrics().heightPixels;
imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
virtualDisplay = mediaProjection.createVirtualDisplay(SCREENCAST, width, height,
density, getVirtualDisplay(), imageReader.getSurface(), null, handler);
imageReader.setOnImageAvailableListener(new ImageAvailableListener(), handler);
}
}```