Skip to content

Screen Recod

Permission Required

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />

Recording Service

class ScreenRecordingService : Service() {
companion object {
var isRecording by mutableStateOf(false)
}
private var mediaRecorder: MediaRecorder? = null
private var virtualDisplay: VirtualDisplay? = null
private var mediaProjection: MediaProjection? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
handleStartForeground()
val default = START_NOT_STICKY
val resultCode =
intent?.getIntExtra("resultCode", Activity.RESULT_CANCELED) ?: return default
val data = intent.getParcelableExtra<Intent>("data") ?: return default
val mediaProjectionManager = getSystemService(MediaProjectionManager::class.java)
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data).also {
it?.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
super.onStop()
stopSelf()
}
}, null)
}
startRecording()
return default
}
private fun startRecording() {
val metrics = resources.displayMetrics
val outputFile = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
"third_${System.currentTimeMillis()}.mp4")
mediaRecorder = MediaRecorder(this).apply {
setVideoSource(MediaRecorder.VideoSource.SURFACE)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setOutputFile(outputFile)
setVideoEncoder(MediaRecorder.VideoEncoder.H264)
setVideoSize(metrics.widthPixels, metrics.heightPixels)
setVideoFrameRate(30)
prepare()
}
virtualDisplay = mediaProjection?.createVirtualDisplay(
"Virtual Screen",
metrics.widthPixels,
metrics.heightPixels,
metrics.densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder?.surface, null, null
)
mediaRecorder?.start()
isRecording = true
}
private fun handleStartForeground() {
val channelId = "record_channel"
val manager = getSystemService(NotificationManager::class.java)
val channel =
NotificationChannel(channelId, "Record Channel", NotificationManager.IMPORTANCE_LOW)
manager.createNotificationChannel(channel)
val notification =
NotificationCompat.Builder(this, channelId)
.setContentTitle("Recording...")
.setSmallIcon(R.drawable.ic_launcher_foreground).build()
startForeground(1, notification)
}
override fun onDestroy() {
super.onDestroy()
runCatching {
mediaRecorder?.stop()
mediaRecorder?.release()
virtualDisplay?.release()
mediaProjection?.stop()
mediaProjection?.stop()
}
}
override fun onBind(p0: Intent?): IBinder? = null
}