在 Android NDK 中配置 ARCore 会话

配置 ARCore 会话,为您的应用打造 AR 体验。

什么是会话?

所有 AR 进程(例如动作跟踪、环境理解和光照估测)都发生在 ARCore 会话内。ArSession 是 ARCore 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);

后续步骤