設定 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);