android - CameraX - 无法配置相机

标签 android android-camerax

我想实现一个自定义 View ,它将使用 Camera X API 显示实时预览,但我坚持使用 Camera X 的配置...

基于CameraX sample code ,我尝试实现我的自定义 View ,但只出现黑屏,并且我的日志显示:

E/Camera: Unable to configure camera 1, timeout!



这是我的 Activity 布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBlack"
    tools:context=".MainActivity">

    <com.component.LiveView
        android:id="@+id/live"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:background="@android:color/black" />

</RelativeLayout>

以及与我的组件相关的代码
override fun onResume() {
    super.onResume()
    when {
        ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED ->
            // Start camera preview
            live.start(this)
        ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) -> ConfirmationDialogFragment.newInstance(R.string.camera_permission_confirmation,
                arrayOf(Manifest.permission.CAMERA),
                REQUEST_CAMERA_PERMISSION,
                R.string.camera_permission_not_granted)
                .show(supportFragmentManager, FRAGMENT_DIALOG)
        else -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),
                REQUEST_CAMERA_PERMISSION)
    }
}

现在,我的Live组件是这样的
class LiveView(context: Context, attrs: AttributeSet) : CameraSourcePreview(context, attrs) {

    init {

        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        } else {
            Timber.plant(TimberReleaseTree())
        }

        Timber.e("LiveView init")
    }

    fun start(livecycleOwner: LifecycleOwner) {
        super.start(livecycleOwner)
        Timber.e("LiveView start")
    }
}

/** Preview the camera image in the screen.  */
open class CameraSourcePreview(context: Context, attrs: AttributeSet) : ViewGroup(context, attrs) {

    private val previewView = PreviewView(context, attrs)

    private var displayId: Int = -1
    private var lensFacing: Int = CameraSelector.LENS_FACING_FRONT
    private var preview: Preview? = null
    private var imageCapture: ImageCapture? = null
    private var imageAnalyzer: ImageAnalysis? = null
    private var camera: Camera? = null

    private val displayManager by lazy {
        context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
    }

    /** Blocking camera operations are performed using this executor */
    private lateinit var cameraExecutor: ExecutorService

    /**
     * We need a display listener for orientation changes that do not trigger a configuration
     * change, for example if we choose to override config change in manifest or for 180-degree
     * orientation changes.
     */
    private val displayListener = object : DisplayManager.DisplayListener {
        override fun onDisplayAdded(displayId: Int) = Unit
        override fun onDisplayRemoved(displayId: Int) = Unit
        override fun onDisplayChanged(displayId: Int) {
            if (displayId == this@CameraSourcePreview.displayId) {
                Timber.d("Rotation changed: ${display.rotation}")
                imageCapture?.targetRotation = display.rotation
                imageAnalyzer?.targetRotation = display.rotation
            }
        }
    }

    /**
     * Starts camera source preview.
     */
    @Throws(IOException::class)
    fun start(lifecycleOwner: LifecycleOwner) {

        Timber.e("CameraSourcePreview start")

        // Initialize our background executor
        cameraExecutor = Executors.newSingleThreadExecutor()

        // Wait for the views to be properly laid out
        addView(previewView)
        //previewView.preferredImplementationMode = PreviewView.ImplementationMode.SURFACE_VIEW // seen on https://stackoverflow.com/a/60559642/10159898 bit it doesn't change anything
        previewView.post {
            // Keep track of the display in which this view is attached
            displayId = previewView.display.displayId
            Timber.e("CameraSourcePreview start post")
            // Bind use cases to lifecycle
            bindCameraUseCases(lifecycleOwner)
        }
    }

    /**
     * Stop camera source preview. It is requirement to implement this part.
     * Recommended to implement it onPause function.
     */
    fun stop() {
        // Shut down our background executor
        cameraExecutor.shutdown()
        Timber.e("CameraSourcePreview stop")
        // Unregister the broadcast receivers and listeners
        displayManager.unregisterDisplayListener(displayListener)
    }

    /** Declare and bind preview, capture and analysis use cases */
    private fun bindCameraUseCases(lifecycleOwner: LifecycleOwner) {
        Timber.e("CameraSourcePreview bindCameraUseCases")
        // Get screen metrics used to setup camera for full screen resolution
        val metrics = DisplayMetrics().also { previewView.display.getRealMetrics(it) }
        Timber.d("Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

        val targetAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels)
        Timber.d("Preview aspect ratio: $targetAspectRatio")

        val targetRotation = previewView.display.rotation

        val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(lensFacing)
                .build()

        // Bind the CameraProvider to the LifeCycleOwner
        val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
        cameraProviderFuture.addListener(Runnable {

            // CameraProvider
            val cameraProvider = cameraProviderFuture.get()

            // Preview Usecase
            preview = Preview.Builder()
                    // We request aspect ratio but no resolution
                    .setTargetAspectRatio(targetAspectRatio)
                    // Set initial target rotation
                    .setTargetRotation(targetRotation)
                    .build()

            // Must unbind the use-cases before rebinding them
            cameraProvider.unbindAll()

            try {
                // A variable number of use-cases can be passed here -
                // camera provides access to CameraControl & CameraInfo
                camera = cameraProvider.bindToLifecycle(
                        lifecycleOwner, cameraSelector, preview)

                preview?.setSurfaceProvider(previewView.createSurfaceProvider(camera?.cameraInfo))
            } catch (exc: Exception) {
                Timber.e("Use case binding failed: ${exc.message}")
            }

        }, ContextCompat.getMainExecutor(context))
    }

    /**
     *  [androidx.camera.core.ImageAnalysisConfig] requires enum value of
     *  [androidx.camera.core.AspectRatio]. Currently it has values of 4:3 & 16:9.
     *
     *  Detecting the most suitable ratio for dimensions provided in @params by counting absolute
     *  of preview ratio to one of the provided values.
     *
     *  @param width - preview width
     *  @param height - preview height
     *  @return suitable aspect ratio
     */
    private fun aspectRatio(width: Int, height: Int): Int {
        Timber.e("CameraSourcePreview aspectRatio")
        val previewRatio = max(width, height).toDouble() / min(width, height)
        if (abs(previewRatio - RATIO_4_3_VALUE) <= abs(previewRatio - RATIO_16_9_VALUE)) {
            return AspectRatio.RATIO_4_3
        }
        return AspectRatio.RATIO_16_9
    }

    /**
     * Recalculate the camera preview size.
     */
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
//        Timber.e("CameraSourcePreview onLayout: $changed, $left, $top, $right, $bottom")
//        var width = 480
//        var height = 640
//        
//        // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
//        if (isPortraitMode) {
//            val tmp = width
//            width = height
//            height = tmp
//        }
//        val layoutWidth = right - left
//        val layoutHeight = bottom - top
//        // Computes height and width for potentially doing fit width.
//        var childWidth = layoutWidth
//        var childHeight = (layoutWidth.toFloat() / width.toFloat() * height).toInt()
//        // If height is too tall using fit width, does fit height instead.
//        if (childHeight > layoutHeight) {
//            childHeight = layoutHeight
//            childWidth = (layoutHeight.toFloat() / height.toFloat() * width).toInt()
//        }
//        for (i in 0 until childCount) {
//            getChildAt(i).layout(0, 0, childWidth, childHeight)
//            Timber.d("Assigned view: $i")
//        }
    }

    companion object {
        private const val RATIO_4_3_VALUE = 4.0 / 3.0
        private const val RATIO_16_9_VALUE = 16.0 / 9.0
    }
}

有人可以看看这个并指出我的问题吗?

笔记 :
  • 我想使用自定义 View ,因为全局目的是迁移我的基于相机库的 ans Camera2
  • 我已经看过 this post about the previewView implementation mode (见代码)但它对我没有帮助。
  • 最佳答案

    我有一个类似的问题。
    请检查您的 list 文件中是否关闭了硬件硬件加速。
    我的 AndroidManifest.xml 中的示例:

    <application
    android:allowBackup="true"
    android:hardwareAccelerated="false" <--- This setting must be removed
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    
       [...]
    
    </application>
    
    我删除了 android:hardwareAccelerated="false"
    在那之后,它就像一个魅力。
    希望它有效。

    关于android - CameraX - 无法配置相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61227001/

    相关文章:

    android - Proguard 未解析的类引用

    android - 在 Android Studio 中组织 java 文件

    android - 使用 ResultReceiver 如果 Activity 被销毁并且 Intent 服务仍在运行会发生什么

    android - 有什么方法可以使用最小 SDK 小于 21 的 Android CameraX API?

    java - "Not Bound To A Valid Camera"CameraX错误

    android - CameraX图像分析的imageproxy大小和PreviewView大小不一样

    java - 连接良好时上传图片,Android(后台进程)

    java - ML Kit Vision - 使用内存图像中的camerax进行条形码检测会导致由于 'int android.graphics.Bitmap.getWidth()'而导致空指针异常

    android - 如何在 CameraX API 中切换相机?

    java - Android HttpUrlConnection 如何将响应读成 fragment