Android 프로그래밍 2

본문 바로가기

사이트 내 전체검색


12. Camera2 실습(1)

페이지 정보

작성자 관리자 댓글 0건 조회 2,985회 작성일 20-12-10 12:00

본문

class QRScan6Activity : AppCompatActivity() {

    private var textureView: TextureView? = null


    private var cameraId: String? = null

    protected var cameraDevice: CameraDevice? = null

    protected var cameraCaptureSessions: CameraCaptureSession? = null


    //protected CaptureRequest captureRequest;

    protected var captureRequestBuilder: CaptureRequest.Builder? = null

    private var imageDimension: Size? = null


    private val REQUEST_CAMERA_PERMISSION = 200

    private var backgroundHandler: Handler? = null

    private var backgroundThread: HandlerThread? = null


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_qrscan)

        setTitle("QRCode Scanner")


        textureView = findViewById(R.id.texture)

        assert(textureView != null)

        textureView!!.setSurfaceTextureListener(textureListener)

    }


    var textureListener: TextureView.SurfaceTextureListener = object : TextureView.SurfaceTextureListener {

        override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {

            //open your camera here

            openCamera()

        }

        override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture,width: Int, height: Int) {

            // Transform you image captured size according to the surface width and height

        }

        override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {

            return false

        }

        override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}

    }


    private fun openCamera() {

        val manager = getSystemService(CAMERA_SERVICE) as CameraManager

        Log.i(TAG, "is camera open")

        try {

            cameraId = manager.cameraIdList[0]

            val characteristics = manager.getCameraCharacteristics(cameraId!!)

            val map = characteristics[CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP]!!

            imageDimension = map.getOutputSizes(SurfaceTexture::class.java)[0]

            // Add permission for camera and let user grant the permission

            if (ActivityCompat.checkSelfPermission(this,

                    Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED

                && ActivityCompat.checkSelfPermission(this,

                    Manifest.permission.WRITE_EXTERNAL_STORAGE )

                !== PackageManager.PERMISSION_GRANTED

            ) {

                ActivityCompat.requestPermissions(

                    this@QRScan6Activity,

                    arrayOf<String>(

                        Manifest.permission.CAMERA,

                        Manifest.permission.WRITE_EXTERNAL_STORAGE

                    ),

                    REQUEST_CAMERA_PERMISSION

                )

                return

            }

            manager.openCamera(cameraId!!, stateCallback, null)

        } catch (e: CameraAccessException) {

            e.printStackTrace()

        }

        Log.i(TAG, "openCamera X")

    }


    private val stateCallback: CameraDevice.StateCallback = object : CameraDevice.StateCallback() {

        override fun onOpened(camera: CameraDevice) {

            //This is called when the camera is open

            Log.i(TAG, "onOpened")

            cameraDevice = camera

            createCameraPreview()

        }


        override fun onDisconnected(camera: CameraDevice) {

            cameraDevice!!.close()

        }


        override fun onError(camera: CameraDevice, error: Int) {

            cameraDevice!!.close()

            cameraDevice = null

        }

    }


    protected fun createCameraPreview() {

        try {

            val texture = textureView!!.surfaceTexture!!

            texture.setDefaultBufferSize(imageDimension!!.width, imageDimension!!.height)

            val surface = Surface(texture)

            captureRequestBuilder =

                cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)

            captureRequestBuilder!!.addTarget(surface)

            cameraDevice!!.createCaptureSession(

                Arrays.asList(surface),

                object : CameraCaptureSession.StateCallback() {

                    override fun onConfigured(@NonNull cameraCaptureSession: CameraCaptureSession) {

                        //The camera is already closed

                        if (null == cameraDevice) {

                            return

                        }

                        // When the session is ready, we start displaying the preview.

                        cameraCaptureSessions = cameraCaptureSession

                        updatePreview()

                    }


                    override fun onConfigureFailed(@NonNull cameraCaptureSession: CameraCaptureSession) {

                        Toast.makeText(this@QRScan6Activity,"Configuration change",

                            Toast.LENGTH_SHORT ).show()

                    }

                },

                null

            )

        } catch (e: CameraAccessException) {

            e.printStackTrace()

        }

    }


    protected fun updatePreview() {

        if (null == cameraDevice) {

            Log.e(TAG, "updatePreview error, return")

        }


        captureRequestBuilder!!.set(

            CaptureRequest.CONTROL_MODE,

            CameraMetadata.CONTROL_MODE_AUTO

        )


        try {

            cameraCaptureSessions!!.setRepeatingRequest(

                captureRequestBuilder!!.build(),

                null,

                backgroundHandler

            )

        } catch (e: CameraAccessException) {

            e.printStackTrace()

        }

    }


    private fun closeCamera() {

        if (null != cameraDevice) {

            cameraDevice!!.close();

            cameraDevice = null;

        }


    }


    override fun onRequestPermissionsResult(

        requestCode: Int,

        permissions: Array<String?>,

        grantResults: IntArray

    ) {

        if (requestCode == REQUEST_CAMERA_PERMISSION) {

            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {

                // close the app

                Toast.makeText(this,"사진촬영 권한이 승인되지 않으면 이앱을 사용할 수 없습니다.",

                    Toast.LENGTH_LONG

                ).show()

                finish()

            }

        }

    }


    override fun onResume() {

        super.onResume()

        Log.i(TAG, "onResume")

        startBackgroundThread()

        if (textureView!!.isAvailable) {

            openCamera()

        } else {

            textureView!!.surfaceTextureListener = textureListener

        }

    }


    override fun onPause() {

        Log.i(TAG, "onPause")

        //captureRequestBuilder!!.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF)

        closeCamera()

        stopBackgroundThread()

        super.onPause()

    }


    protected fun startBackgroundThread() {

        backgroundThread = HandlerThread("Camera Background")

        backgroundThread!!.start()

        backgroundHandler = Handler(backgroundThread!!.getLooper())

    }


    protected fun stopBackgroundThread() {

        backgroundThread!!.quitSafely()

        try {

            backgroundThread!!.join()

            backgroundThread = null

            backgroundHandler = null

        } catch (e: InterruptedException) {

            e.printStackTrace()

        }

    }


댓글목록

등록된 댓글이 없습니다.



개인정보취급방침 서비스이용약관
Copyright © www.leelab.co.kr All rights reserved.
상단으로
TEL. 063-469-4551 FAX. 063-469-4560
전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과
PC 버전으로 보기