Android CameraX 開啟攝像頭預覽

AnRFDev發表於2021-12-10

目標很簡單,用CameraX開啟攝像頭預覽,實時顯示在介面上。看看CameraX有沒有Google說的那麼好用。先按最簡單的來,把預覽顯示出來。

引入依賴

模組gradle的一些配置,使用的Android SDK版本為31,啟用了databinding

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 31
    buildToolsVersion "31.0.0"
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 31
    }
    dataBinding {
        enabled = true
    }
}

引入CameraX依賴(CameraX 核心庫是用camera2實現的),目前主要用1.1.0-alpha11版本

dependencies {
    implementation "androidx.camera:camera-core:1.1.0-alpha11"
    implementation "androidx.camera:camera-camera2:1.1.0-alpha11"
    implementation "androidx.camera:camera-lifecycle:1.1.0-alpha11"
    implementation "androidx.camera:camera-view:1.0.0-alpha31"
    implementation "androidx.camera:camera-extensions:1.0.0-alpha31"
}

使用1.0.2版本的CameraX核心庫會報錯,找不到getOrCreateInstance方法。

??? bug "NoSuchMethodError getOrCreateInstance"

```log
CrashHandler: In thread: Thread[main,5,main]
    UncaughtException detected: java.lang.NoSuchMethodError: No static method getOrCreateInstance(Landroid/content/Context;)Lcom/google/common/util/concurrent/ListenableFuture; in class Landroidx/camera/core/CameraX; or its super classes (declaration of 'androidx.camera.core.CameraX' appears in /data/app/com.rustfisher.tutorial2020-1/base.apk)
    at androidx.camera.lifecycle.ProcessCameraProvider.getInstance(ProcessCameraProvider.java:149)
    at com.rustfisher.tutorial2020.camera.SimplePreviewXAct.onCreate(SimplePreviewXAct.java:36)
    at android.app.Activity.performCreate(Activity.java:6161)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2507)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2640)
    at android.app.ActivityThread.access$800(ActivityThread.java:182)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5682)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
```

許可權

需要動態申請android.permission.CAMERA許可權

<uses-permission android:name="android.permission.CAMERA" />

本文略過動態申請許可權的地方

介面

CameraX為開發者貼心地準備了androidx.camera.view.PreviewView

把它放在一個FrameLayout裡,如下的act_simple_preivew_x.layout

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.camera.view.PreviewView
            android:id="@+id/previewView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </FrameLayout>
</layout>

開啟預覽

在activity中開啟相機預覽

// SimplePreviewXAct.java
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;
// import com.rustfisher.tutorial2020.R;
// import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding;

import java.util.concurrent.ExecutionException;

public class SimplePreviewXAct extends AppCompatActivity {

    private ActSimplePreivewXBinding mBinding;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.act_simple_preivew_x);
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                // 這裡不用處理
            }
        }, ContextCompat.getMainExecutor(this));
    }

    void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder().build();

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider());

        Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview);
    }
}

注意我們這裡使用的是androidx.appcompat.app.AppCompatActivity

為了獲得ProcessCameraProvider,用ProcessCameraProvider.getInstance方法拿到一個cameraProviderFuture
cameraProviderFuture完成後取出ProcessCameraProvidercameraProvider)。

要開啟預覽,通過Preview.Builder構建一個Preview。用CameraSelector來選擇後置攝像頭。
PreviewSurfaceProvider由layout中的androidx.camera.view.PreviewView提供。

cameraProvider.bindToLifecycle繫結上後,啟動攝像頭預覽

執行測試

執行到手機上,開啟這個Activity就可以看到攝像頭預覽。影像寬高比正常,沒有拉伸現象。

  • 榮耀 EMUI 3.1 Lite,Android 5.1 執行正常
  • Redmi 9A,MIUI 12.5.1穩定版,Android 10 執行正常
  • 一加5,H2OS 10.0.3,Android 10 執行正常

增加開關

在layout里加2個按鈕,控制相機開關

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:gravity="center"
            android:orientation="horizontal"
            android:padding="4dp">

            <Button
                android:id="@+id/start"
                style="@style/NormalBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="開啟" />

            <Button
                android:id="@+id/end"
                style="@style/NormalBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="12dp"
                android:text="關閉" />
        </LinearLayout>

        <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.camera.view.PreviewView
                android:id="@+id/previewView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

    </LinearLayout>
</layout>

根layout換成LinearLayout

修改bindPreview方法,先檢查傳入的ProcessCameraProvider是否為空

private void bindPreview(ProcessCameraProvider cameraProvider) {
    if (cameraProvider == null) {
        Toast.makeText(getApplicationContext(), "沒獲取到相機", Toast.LENGTH_SHORT).show();
        return;
    }
    Preview preview = new Preview.Builder().build();

    CameraSelector cameraSelector = new CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build();

    preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider());

    Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview);
}

修改後的activity部分程式碼

import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.google.common.util.concurrent.ListenableFuture;
// import com.rustfisher.tutorial2020.R;
// import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding;

import java.util.concurrent.ExecutionException;

public class SimplePreviewXAct extends AppCompatActivity {

    private ActSimplePreivewXBinding mBinding;
    private ListenableFuture<ProcessCameraProvider> mCameraProviderFuture;
    private ProcessCameraProvider mCameraProvider;
    private boolean mRunning = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.act_simple_preivew_x);
        mCameraProviderFuture = ProcessCameraProvider.getInstance(this);
        mCameraProviderFuture.addListener(() -> {
            try {
                mCameraProvider = mCameraProviderFuture.get();
            } catch (ExecutionException | InterruptedException e) {
                // 這裡不用處理
            }
        }, ContextCompat.getMainExecutor(this));
        mBinding.start.setOnClickListener(v -> {
            if (mCameraProvider != null && !mRunning) {
                bindPreview(mCameraProvider);
            }
        });
        mBinding.end.setOnClickListener(v -> {
            mCameraProvider.unbindAll();
            mRunning = false;
        });
    }

    private void bindPreview(ProcessCameraProvider cameraProvider) {
        if (cameraProvider == null) {
            Toast.makeText(getApplicationContext(), "沒獲取到相機", Toast.LENGTH_SHORT).show();
            return;
        }
        Preview preview = new Preview.Builder().build();

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider());

        Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview);
        mRunning = true;
    }
}

拿到mCameraProvider後不要立刻繫結生命週期。

如果要開啟預覽,則呼叫bindPreview(mCameraProvider)。記錄一下現在相機已經開啟預覽mRunning = true

如果要停止預覽,則解綁生命週期mCameraProvider.unbindAll()。這個方法需要在主執行緒呼叫。

執行起來後,可以用按鈕來控制相機預覽的開關。相比之前,PreviewView的高度變小了一點(讓了點位置給按鈕)。
但視訊寬高比例正常,沒有被拉伸。預設的配置下,還有自動對焦的功能。

小結

從簡單的開啟相機預覽來看,CameraX簡化了開發者的工作。提供了PreviewView,開發者不需要自定義SurfaceView或者TextureView。實時預覽中,相機能夠自動對焦。本文用的是1.1.0-alpha11,而CameraX還在發展之中。

參考

原文連結CameraX 開啟攝像頭預覽

相關文章