본문 바로가기
Android

[Kotlin] Android Camera 사용하기

by bryan.oh 2023. 8. 4.
반응형

Android Camera 사용하기
권한

카메라를 사용하기 위해서는 카메라 권한부터 얻어야 합니다.

흐름은 아래와 같습니다.

Manifest 에 다음 항목 추가

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.CAMERA" />
    
    ..생략..

 

dependencies 추가

 

build.gradle(app) 의 dependencies 에 다음 항목 추가하고 우측상단에 [Sync Now] 클릭해서 받아옵니다.

    def camerax_version = "1.0.0-rc01"
    def camerax_view_version = "1.0.0-alpha20"

    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"
    implementation "androidx.camera:camera-view:${camerax_view_version}"

 

코틀린으로 CameraTestActivity 생성

class CameraTestActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCameraTestBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCameraTestBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

ViewBinding 으로 설정 했습니다.

 

layout 에 PreviewView 추가

    <androidx.camera.view.PreviewView
        android:id="@+id/cameraView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

 

 

권한이 있는지 체크

    private fun hasCameraPermission() =
        ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED

 

권한 요청

    private fun requestPermission(){
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            CAMERA_PERMISSION_REQUEST_CODE
        )
    }

 

사용자에게 권한을 요청 한 후 결과를 수신하는 코드

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 권한을 받았음~~
            bindCameraUseCases()
        } else {
            // 권한을 못 받음!!
            Toast.makeText(this,
                "Camera permission required",
                Toast.LENGTH_LONG
            ).show()
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

 

카메라 사용

    private fun bindCameraUseCases() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()

            // setting up the preview use case
            val previewUseCase = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(binding.cameraView.surfaceProvider)
                }

            // configure to use the back camera
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

            try {
                cameraProvider.bindToLifecycle(
                    this,
                    cameraSelector,
                    previewUseCase)
            } catch (illegalStateException: IllegalStateException) {
                // If the use case has already been bound to another lifecycle or method is not called on main thread.
                Log.e(TAG, illegalStateException.message.orEmpty())
            } catch (illegalArgumentException: IllegalArgumentException) {
                // If the provided camera selector is unable to resolve a camera to be used for the given use cases.
                Log.e(TAG, illegalArgumentException.message.orEmpty())
            }
        }, ContextCompat.getMainExecutor(this))
    }
위코드에서 TAG 를 사용하기 아래 코드 추가.

companion object {
    val TAG: String = MainActivity::class.java.simpleName
}

 

import 참고

import android.Manifest
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import 자신의_패키지_경로_입력.databinding.ActivityBarcodeScanBinding

 

 

실제 폰으로 디버깅 실행.

결과

728x90
반응형

댓글