Menggunakan sesi peningkatan cahaya redup

Gunakan sesi peningkatan cahaya redup untuk mengaktifkan dan menonaktifkan Peningkatan Cahaya Redup Google.

Kotlin

dependencies {
  val low_light_boost_version = "16.0.0-beta01"
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2")
  implementation("com.google.android.gms:play-services-base:18.7.0")
  implementation("com.google.android.gms:play-services-camera-low-light-boost:${low_light_boost_version}")
  implementation("com.google.android.gms:play-services-tasks:18.3.0")
}

Groovy

dependencies {
  def low_light_boost_version = "16.0.0-beta01"
  implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2'
  implementation 'com.google.android.gms:play-services-base:18.7.0'
  implementation 'com.google.android.gms:play-services-camera-low-light-boost:${low_light_boost_version}'
  implementation 'com.google.android.gms:play-services-tasks:18.3.0'
}

LowLightBoostSession disediakan oleh paket com.google.android.gms.cameralowlight layanan Google Play. Lihat dokumentasi layanan Google Play untuk mengetahui informasi tentang mengakses API layanan Google Play.

Membuat objek callback

Saat membuat sesi peningkatan cahaya redup, Anda harus meneruskan objek yang mengimplementasikan antarmuka LowLightBoostCallback. Fungsi objek ini dipanggil saat sesi terputus atau dihancurkan. Kode berikut menunjukkan cara membuat callback:

Kotlin

private fun createLowLightBoostCallback(): LowLightBoostCallback =
  object : LowLightBoostCallback() {
    override fun onSessionDestroyed() {
      Log.d(TAG, "onSessionDestroyed")
      lowLightBoostSession = null
    }

    override fun onSessionDisconnected(statusCode: Int) {
      Log.d(TAG, "onSessionDisconnected: error=$statusCode")
      lowLightBoostSession = null
    }
  }

Java

private LowLightBoostCallback createLowLightBoostCallback() {
  LowLightBoostCallback lowLightBoostCallback = new LowLightBoostCallback() {
    @Override
    public void onSessionDestroyed() {
      Log.d(TAG, "onSessionDestroyed");
      lowLightBoostSession = null;
    }

    @Override
    public void onSessionDisconnected(int statusCode) {
      Log.d(TAG, "onSessionCreationFailed: error=" + statusCode);
      lowLightBoostSession = null;
    }
  }
  return lowLightBoostCallback;
}

Poin penting tentang kode ini

  • Kode ini menentukan metode pribadi, createLowLightBoostCallback(), yang membuat objek callback. Anda akan memanggil metode tersebut saat benar-benar membuat sesi peningkatan cahaya redup, seperti yang dijelaskan dalam Membuat sesi.
  • Callback dipanggil saat sesi terputus atau dihancurkan. Metode ini tidak dipanggil saat sesi dibuat. Untuk memeriksa apakah sesi berhasil dibuat, periksa objek Task yang ditampilkan oleh LowLightBoostClient.createSession.

Membuat sesi

Untuk membuat sesi cahaya redup, panggil metode LowLightBoostClient.createSession.

Kotlin

val options = LowLightBoostOptions(
  previewSurface,
  cameraId,
  previewWidth,
  previewHeight,
  enableLowLightBoost
)

launch {
  try {
    val lowLightBoostSession = lowLightBoostClient
      .createSession(options, createLowLightBoostCallback()).await()

    Log.d(TAG, "Session created successfully")

    // Get the surface from the LLB session;
    // give it to camera so camera can write frames to it
  } catch (e: CancellationException) {
    Log.w(TAG, "Session creation was canceled", e)
    lowLightBoostSession = null
  } catch (e: ApiException) {
    Log.e(TAG, "Session creation failed with ApiException:", e)
    lowLightBoostSession = null
  } catch (e: Exception) {
    Log.e(TAG, "Session creation failed with Exception", e)
    lowLightBoostSession = null
  }
}

Java

LowLightBoostOptions options = new LowLightBoostOptions(
  previewSurface,
  cameraId,
  previewWidth,
  previewHeight,
  enableLowLightBoost);

lowLightBoostClient
  .createSession(options, createLowLightBoostCallback())
  .addOnSuccessListener(
    lowLightBoostExecutor,
    (session) -> {
      Log.d(TAG, "Session created successfully");

      // Get the surface from the LLB session;
      // give it to camera so camera can write frames to it

    })
  .addOnFailureListener(
    lowLightBoostExecutor,
    (e) -> {
      ApiException apiException = (ApiException) e;
      Log.d(TAG, "Session creation failed: " + e);
      lowLightBoostSession = null;
    })
  .addOnCompleteListener(
    lowLightBoostExecutor,
    (task) -> Log.d(TAG, "Session creation complete"))
  .addOnCanceledListener(
    lowLightBoostExecutor,
    () -> {
      throw new RuntimeException("Session creation canceled");
    });

Poin penting tentang kode ini

  • Anda meneruskan objek LowLightBoostOptions ke createSession() untuk mengonfigurasi sesi. Objek ini menentukan hal-hal seperti platform target, ID kamera yang akan digunakan, dan dimensi pratinjau.
  • Kode ini mengasumsikan bahwa Anda telah membuka koneksi ke kamera Camera2, dan menggunakan informasi tersebut untuk menetapkan nilai cameraId, previewWidth, previewHeight. Untuk informasi selengkapnya, lihat dokumentasi Camera2.
  • enableLowLightBoost adalah nilai boolean yang menentukan apakah peningkatan cahaya rendah harus dimulai atau dinonaktifkan.
  • createLowLightBoostCallback adalah metode yang Anda tulis untuk membuat objek callback. Objek ini dipanggil saat sesi terputus atau dihancurkan.
  • Metode LowLightBoostClient.createSession() menampilkan objek Task. Anda menggunakan objek ini untuk menyiapkan pemroses keberhasilan dan kegagalan. Rekam video di dalam pemroses keberhasilan.
  • Anda dapat menentukan Executor untuk menjalankan pemroses. Jika Anda tidak menentukan Executor, pemroses akan berjalan di thread utama. Dalam kode ini, kita mengasumsikan lowLightBoostExecutor adalah Executor yang sesuai.

Memulai pratinjau kamera

Setelah membuat sesi cahaya redup, Anda dapat memulai streaming pratinjau kamera. Anda harus melakukannya di dalam callback onSuccess() yang diteruskan ke sesi cahaya redup, seperti yang dijelaskan dalam Membuat sesi. Kode berikut menunjukkan cara merekam video:

Kotlin

MainActivity.this.lowLightBoostSession =
  lowLightBoostSession
MainActivity.this.lowLightBoostSession
  .setSceneDetectorCallback(
    (lowLightBoostSession, boostStrength) -> {
      Log.d(TAG, "onSceneBrightnessChanged: " +
        "boostStrength=$boostStrength")
      // boostStrength > 0.5 indicates a low light scene.
      // Update UI accordingly.
    },
    lowLightBoostExecutor
  )
try {
  startCaptureSession(
    lowLightBoostSession.getCameraSurface())
    // Start a Camera2 session here. Pass the LLB surface
    // to the camera so the camera can write frames to it.
} catch (e: CameraAccessException) {
  Log.e(TAG, "Failed to start capture session", e)
  // Must try again or start the capture session without LLB.
}

Java

MainActivity.this.lowLightBoostSession =
  lowLightBoostSession;
MainActivity.this.lowLightBoostSession
  .setSceneDetectorCallback(
    (lowLightBoostSession, boostStrength) -> {
      Log.d(TAG, "onSceneBrightnessChanged: " +
        "boostStrength=" + boostStrength);
      // boostStrength > 0.5 indicates a low light scene.
      // Update UI accordingly.
    },
    lowLightBoostExecutor
  );
try {
  startCaptureSession(
    lowLightBoostSession.getCameraSurface());
    // Start a Camera2 session here. Pass the LLB surface
    // to the camera so the camera can write frames to it.
} catch (CameraAccessException e) {
  Log.e(TAG, "Failed to start capture session", e);
  // Must try again or start the capture session without LLB.
}

Poin penting tentang kode ini

Merilis sesi

Saat kamera tidak lagi aktif, lepaskan sesi peningkatan cahaya redup dengan memanggil LowLightBoostSession.release(). Secara khusus, Anda harus memastikan untuk melepaskan sesi saat aktivitas dihancurkan. Anda dapat melakukannya dengan memanggil metode dalam metode onDestroy() aktivitas:

Kotlin

override protected void onDestroy() {
  super.onDestroy()
  if (lowLightBoostSession != null) {
    lowLightBoostSession.release()
    lowLightBoostSession = null
  }
}

Java

@Override
protected void onDestroy() {
  super.onDestroy();
  if (lowLightBoostSession != null) {
    lowLightBoostSession.release();
    lowLightBoostSession = null;
  }
}

Poin penting tentang kode ini

  • Setelah sesi dirilis, Anda tidak boleh memanggil metode apa pun. Anda harus menghapus variabel apa pun yang mengarah ke sesi, seperti yang dilakukan kode ini.