Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MainActivity : AppCompatActivity() {
...
private lateinit var previewView : PreviewView
private lateinit var cameraProviderListenableFuture : ListenableFuture<ProcessCameraProvider>
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
previewView = findViewById( R.id.camera_preview_view )
...
}
private fun setupCameraProvider() {
cameraProviderListenableFuture = ProcessCameraProvider.getInstance( this )
cameraProviderListenableFuture.addListener({
try {
val cameraProvider: ProcessCameraProvider = cameraProviderListenableFuture.get()
bindPreview(cameraProvider)
}
catch (e: ExecutionException) {
Log.e("APP", e.message!!)
}
catch (e: InterruptedException) {
Log.e("APP", e.message!!)
}
}, ContextCompat.getMainExecutor( this ))
}
private fun bindPreview(cameraProvider: ProcessCameraProvider) {
val preview = Preview.Builder().build()
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_FRONT)
.build()
preview.setSurfaceProvider(previewView.surfaceProvider)
val displayMetrics = resources.displayMetrics
val screenSize = Size( displayMetrics.widthPixels, displayMetrics.heightPixels)
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution( screenSize )
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
cameraProvider.bindToLifecycle(
(this as LifecycleOwner),
cameraSelector,
preview
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment