I have a foreground service which contains a floating action button which appears on screen overlay over other applications, the service is started from fragment. Now what I want to do is to start media projection when the service is started, it will monitor screen activity and media recorder will record it into a mp4 file. The problem is that how can I get result from media Projection when I start the media projection and service from Fragment. is there any way to get results from Media Projection in Fragment?
if I do it main Activity like below it will work like this
class MainActivity : AppCompatActivity() {
// ...
private lateinit var mediaRecorder: MediaRecorder
private lateinit var mediaProjectionManager: MediaProjectionManager
private lateinit var mediaProjection: MediaProjection // Need to handle the projection permission
private fun setupMediaRecorder() {
mediaRecorder = MediaRecorder()
mediaProjectionManager =
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
// You need to handle the projection permission and assign the mediaProjection variable
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE)
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
mediaRecorder.setOutputFile(getOutputFilePath()) // Define this function to get the file path
val displayMetrics = resources.displayMetrics
val screenDensity = displayMetrics.densityDpi
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
mediaRecorder.setVideoSize(screenWidth, screenHeight)
mediaRecorder.setVideoFrameRate(30)
mediaRecorder.setVideoEncodingBitRate(1000000)
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264)
try {
mediaRecorder.prepare()
} catch (e: Exception) {
e.printStackTrace()
}
}
// ...
// Start recording
private fun startRecording() {
val mediaProjectionIntent = mediaProjectionManager.createScreenCaptureIntent()
startActivityForResult(mediaProjectionIntent, PERMISSIONS_REQUEST_CODE)
}
// Implement onActivityResult() to handle the result of the media projection permission request
// Stop recording
private fun stopRecording() {
mediaRecorder.stop()
mediaRecorder.release()
// Release the media projection
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == PERMISSIONS_REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data!!)
val virtualDisplay = mediaProjection.createVirtualDisplay(
"Recording Display",
screenWidth,
screenHeight,
screenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder.surface,
null,
null
)
mediaRecorder.start()
}
}
}