在 Android NDK 中設定 ARCore 工作階段

設定 ARCore 工作階段,為您的應用程式打造 AR 體驗。

什麼是工作階段?

所有 AR 程序,例如動作追蹤 透過 ARCore 技術瞭解環境知識,以及估算亮度 會很有幫助ArSession 是 ARCore 的主要進入點 也能使用 Google Cloud CLI 或 Compute Engine API可管理 AR 系統狀態並處理工作階段生命週期 應用程式,建立、設定、開始或停止工作階段。最重要的是 應用程式即可接收允許存取相機圖片的影格 姿勢。

這個工作階段可用於設定下列功能:

確認 ARCore 已安裝且為最新版本

建立 ArSession 前,請確認 ARCore 已安裝且為最新版本。 如未安裝 ARCore,工作階段建立作業就會失敗,且後續任何後續作業 必須重新啟動應用程式,才能安裝或升級 ARCore。

/*
 * Check if ARCore is currently usable, i.e. whether ARCore is supported and
 * up to date.
 */
int32_t is_arcore_supported_and_up_to_date(void* env, void* context) {
  ArAvailability availability;
  ArCoreApk_checkAvailability(env, context, &availability);
  switch (availability) {
    case AR_AVAILABILITY_SUPPORTED_INSTALLED:
      return true;
    case AR_AVAILABILITY_SUPPORTED_APK_TOO_OLD:
    case AR_AVAILABILITY_SUPPORTED_NOT_INSTALLED: {
      ArInstallStatus install_status;
      // ArCoreApk_requestInstall is processed asynchronously.
      CHECK(ArCoreApk_requestInstall(env, context, true, &install_status) ==
            AR_SUCCESS);
      return false;
    }
    case AR_AVAILABILITY_UNSUPPORTED_DEVICE_NOT_CAPABLE:
      // This device is not supported for AR.
      return false;
    case AR_AVAILABILITY_UNKNOWN_CHECKING:
      // ARCore is checking the availability with a remote query.
      // This function should be called again after waiting 200 ms
      // to determine the query result.
      handle_check_later();
      return false;
    case AR_AVAILABILITY_UNKNOWN_ERROR:
    case AR_AVAILABILITY_UNKNOWN_TIMED_OUT:
      // There was an error checking for AR availability.
      // This may be due to the device being offline.
      // Handle the error appropriately.
      handle_unknown_error();
      return false;

    default:  // All enum cases have been handled.
      return false;
  }
}

建立工作階段

在 ARCore 中建立並設定工作階段。

// Create a new ARCore session.
ArSession* ar_session = NULL;
CHECK(ArSession_create(env, context, &ar_session) == AR_SUCCESS);

// Create a session config.
ArConfig* ar_config = NULL;
ArConfig_create(ar_session, &ar_config);

// Do feature-specific operations here, such as enabling depth or turning on
// support for Augmented Faces.

// Configure the session.
CHECK(ArSession_configure(ar_session, ar_config) == AR_SUCCESS);

關閉工作階段

ArSession 擁有大量的原生堆積記憶體。失敗 明確關閉工作階段可能會導致應用程式 用盡原生記憶體 當機。不再需要 AR 工作階段時,請呼叫 ArSession_destroy()敬上 釋出資源

// Release memory used by the AR session.
ArSession_destroy(session);

後續步驟