在 Android NDK 應用程式中啟用 AR

啟用 AR,即可在新應用程式或現有應用程式中使用擴增實境功能。

將應用程式設為「需要 AR」或「支援 AR」

為節省個別裝置的空間,所有 AR 功能都儲存在名為「Google Play 服務 - AR 適用」的應用程式中,並由 Play 商店另行更新。使用 AR 功能的 Android 應用程式會透過 ARCore SDK 與「Google Play 服務 - AR 適用」通訊。支援 AR 功能的應用程式可透過兩種方式設定:AR 必要AR 選用。這項指定項目會決定應用程式與「Google Play 服務 - AR 適用」應用程式的互動方式。

AR 必備應用程式必須有 ARCore 才能運作。必須使用支援 ARCore 的裝置,並安裝「Google Play 服務 - AR 適用」才能使用。

  • Google Play 商店只會在支援 ARCore 的裝置上提供「AR 必備」應用程式。
  • 使用者安裝 AR 必要應用程式時,Google Play 商店會自動在裝置上安裝「Google Play 服務 - AR 適用」。不過,如果 Google Play 服務 - AR 適用過時或已手動解除安裝,應用程式仍須執行額外的執行階段檢查

AR 選擇性應用程式會使用 ARCore 強化現有功能。這項功能提供選用的 AR 功能,只有在已安裝「Google Play 服務 - AR 適用」的 ARCore 支援裝置上才會啟用。

  • 即使裝置不支援 ARCore,也能安裝及執行 AR 選擇性應用程式。
  • 使用者安裝 AR 選擇性應用程式時,Google Play 商店不會在裝置上自動安裝「Google Play 服務 - AR 適用」。
AR RequiredAR 選用
AR 功能使用情況 應用程式需要 ARCore 才能提供基本功能。 ARCore 可擴增應用程式的功能,您的應用程式可以在沒有 ARCore 支援的情況下執行。
Play 商店顯示設定 應用程式只會顯示在支援 ARCore 的裝置上。 應用程式遵循一般上架程序
「Google Play 服務 - AR 適用」安裝方法 Play 商店會在安裝應用程式時,一併安裝「Google Play 服務 - AR 適用」。 您的應用程式會使用 ArCoreApk.requestInstall() 下載及安裝 ARCore。
Android minSdkVersion 需求條件 Android 7.0 (API 級別 24) Android 4.4 (API 級別 19),但執行任何 AR 功能至少需要 Android 7.0 (API 級別 24)
必須使用 ArCoreApk_checkAvailability()ArCoreApk_checkAvailabilityAsync() 檢查 ARCore 支援和安裝狀態
必須使用 ArCoreApk.requestInstall() 安裝「Google Play 服務 - AR 適用」

如要將應用程式設為「需要 AR」或「可選用 AR」,請更新 AndroidManifest.xml,加入下列項目:

AR Required

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

<!-- Limits app visibility in the Google Play Store to ARCore supported devices
     (https://developers.google.com/ar/devices). -->
<uses-feature android:name="android.hardware.camera.ar" />

<application >
    

    <!-- "AR Required" app, requires "Google Play Services for AR" (ARCore)
         to be installed, as the app does not include any non-AR features. -->
    <meta-data android:name="com.google.ar.core" android:value="required" />
</application>

AR 選用

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

<!-- If your app was previously AR Required, don't forget to remove the
     `<uses-feature android:name="android.hardware.camera.ar" />` entry, as
     this would limit app visibility in the Google Play Store to only
     ARCore supported devices. -->

<application >
    

    <!-- "AR Optional" app, contains non-AR features that can be used when
         "Google Play Services for AR" (ARCore) is not available. -->
    <meta-data android:name="com.google.ar.core" android:value="optional" />
</application>

然後修改應用程式的 build.gradle,指定至少 24minSdkVersion

 android {
     defaultConfig {
         …
         minSdkVersion 24
     }
 }

新增建構依附元件

  1. 確認專案的 build.gradle 檔案包含 Google 的 Maven 存放區。

    allprojects {
        repositories {
            google()
            …
        }
    }
    
  2. 在模組的 build.gradle 檔案中新增自訂工作,從 ARCore AAR 檔案中擷取內含的原生程式庫。這樣一來,就能在 C 或 C++ 專案中直接參照這些函式庫。

  3. app/build 目錄中,定義要將原生程式庫解壓縮至哪個目錄的變數。

  4. 建立 Gradle 設定來保存資料和擷取工作。

    /*
    The ARCore AAR library contains native shared libraries that are
    extracted before building to a temporary directory.
    */
    def arcore_libpath = "${buildDir}/arcore-native"
    
    // Create a configuration to mark which aars to extract .so files from
    configurations { natives }
    
  5. 建立工作,從 AAR 檔案複製原生程式庫,並將其新增至建構依附元件。

    // Extracts the shared libraries from AARs in the native configuration
    // so that NDK builds can access these libraries.
    task extractNativeLibraries() {
       // Extract every time.
       outputs.upToDateWhen { false }
    
       doFirst {
            configurations.natives.files.each { f ->
                copy {
                    from zipTree(f)
                    into arcore_libpath
                    include "jni/**/*"
                }
            }
        }
    }
    
    tasks.whenTaskAdded {
        task-> if (task.name.contains("external") && !task.name.contains("Clean")) {
            task.dependsOn(extractNativeLibraries)
        }
    }
    
  6. 設定原生建構標記,將位置傳遞至外部建構工具。

    // From the sample app.
    externalNativeBuild {
        cmake {
            cppFlags "-std=c++11", "-Wall"
            arguments "-DANDROID_STL=c++_static",
                    "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                    "-DARCORE_INCLUDE=${project.rootDir}/../../libraries/include"
        }
    }
    
  7. 新增 Java 和原生程式庫的依附元件。

    dependencies {
         ...
         // Add Java and native dependencies to the ARCore library.
         implementation 'com.google.ar:core:1.33.0'
         natives 'com.google.ar:core:1.33.0'
         ...
    }
    
  8. CMakeLists.txt 中參照原生程式庫。

    # Import the ARCore library.
    add_library(arcore SHARED IMPORTED)
    set_target_properties(arcore PROPERTIES IMPORTED_LOCATION
                  ${ARCORE_LIBPATH}/${ANDROID_ABI}/libarcore_sdk_c.so
                  INTERFACE_INCLUDE_DIRECTORIES ${ARCORE_INCLUDE}
    )
    

執行執行階段檢查

在執行階段,請執行下列操作,確保應用程式的 AR 功能順暢運作。

確認是否支援 ARCore

「AR 必要」和「AR 選用」應用程式都應使用 ArCoreApk_checkAvailability()ArCoreApk_checkAvailabilityAsync(),判斷目前裝置是否支援 ARCore。如果裝置不支援 ARCore,應用程式應停用 AR 相關功能,並隱藏相關聯的使用者介面元素。

Android NDK 應用程式可以使用 Java ArCoreApk 類別,在原生 C ARCore Session API 中檢查相容性及管理安裝作業。由於涉及大量錯誤處理和使用者介面互動,因此相較於使用 ArCoreApk_ 函式,這可能更容易。

void maybeEnableArButton(JNIEnv env, jobject context) {
  // Likely called from Activity.onCreate() of an activity with AR buttons.
  ArAvailability availability
  ArCoreApk_checkAvailability(env, context, &availability);
  if (availability == AR_AVAILABILITY_UNKNOWN_CHECKING) {
    // Set a timer to call maybeEnableArButton() again after about 200ms.
  }
  if (availability == AR_AVAILABILITY_SUPPORTED_NOT_INSTALLED ||
      availability == AR_AVAILABILITY_SUPPORTED_APK_TOO_OLD ||
      availability == AR_AVAILABILITY_SUPPORTED_INSTALLED) {
    // Show or enable the AR button.
  } else {
    // Hide or disable the AR button.
  }
}
即使「Google Play 服務 - AR 適用」是與 AR 必要應用程式一併安裝,不支援的裝置使用者仍可能從外部來源安裝。使用 ArCoreApk_checkAvailability()ArCoreApk_checkAvailabilityAsync() 檢查 ARCore 支援情形,可確保體驗一致性。

ArCoreApk_checkAvailability() 可能需要查詢網路資源,判斷裝置是否支援 ARCore。在這段期間,系統會傳回 AR_AVAILABILITY_UNKNOWN_CHECKING。為減少感知延遲和彈出視窗,應用程式應在生命週期初期呼叫 ArCoreApk_checkAvailability() 一次,以啟動查詢,並忽略傳回的值。這樣一來,系統顯示可能進入 AR 的 UI 元素時,就能立即提供快取結果。

確認是否已安裝「Google Play 服務 - AR 適用」

「AR 必備」和「AR 選用」應用程式都必須使用 ArCoreApk.requestInstall() 建立 ARCore 工作階段,檢查是否已 (仍) 安裝相容版本的「Google Play 服務 - AR 適用」,並確保已下載所有必要的 ARCore 裝置設定檔資料。

// Tracks if an installation request has already been triggered.
bool install_requested_;

void nativeOnCreate() {
  // Do other setup here.

  install_requested_ = false;
}

void nativeOnResume(JNIEnv env, jobject activity) {
  if (ar_session_ == null) {
    bool user_requested_install = !install_requested_;

    ArInstallStatus install_status;
    // Ensure that Google Play Services for AR and ARCore device profile data are
    // installed and up to date.
    ArStatus error = ArCoreApk_requestInstall(
        env, activity, user_requested_install, &install_status);
    if (error != AR_SUCCESS) {
      // Inform user of error.
      return;
    }

    switch (install_status) {
      case AR_INSTALL_STATUS_INSTALLED:
        break;
      case AR_INSTALL_STATUS_INSTALL_REQUESTED:
        // When this method returns AR_INSTALL_STATUS_INSTALL_REQUESTED:
        // 1. This activity will be paused.
        // 2. The user is prompted to install or update Google Play
        //    Services for AR (market://details?id=com.google.ar.core).
        // 3. ARCore downloads the latest device profile data.
        // 4. This activity is resumed. The next invocation of
        //    ArCoreApk_requestInstall() will either return
        //    AR_INSTALL_STATUS_INSTALLED or throw an exception if the
        //    installation or update did not succeed.
        install_requested_ = true;
        return;
    }

    // Request camera permissions.

    error = ArSession_create(env, context, &ar_session_);
    if (error != AR_SUCCESS) {
      // Inform user of error.
      return;
    }

    // Configure the ARCore session.
  }

  // Normal onResume behavior.
}

遵守使用者隱私權規定

如要在 Play 商店發布應用程式,請確認應用程式符合 ARCore 的使用者隱私權規定

後續步驟