Старая облачная конечная точка
ARCore Cloud Anchor API устарела и не будет поддерживаться после 31 августа 2023 года. Если ваше приложение использует этот API, вы должны как можно скорее
обновить его , чтобы использовать новую облачную конечную точку
ARCore API .
Краткое руководство по Cloud Anchors для Android
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Попробуйте разместить и разрешить облачные привязки в примерах приложений cloud_anchor_java
и persistent_cloud_anchor_java
.
Какой пример приложения вам следует использовать?
Облачные привязки — это привязки , размещенные в конечной точке облака API ARCore . Этот API позволяет пользователям обмениваться опытом в одном приложении. Постоянные облачные привязки — это облачные привязки, которые могут размещаться более 24 часов.
-
persistent_cloud_anchor_java
— это реализация варианта использования совместного проекта. Он использует авторизацию без ключа для авторизации вызовов API ARCore. Поскольку для обмена идентификаторами Cloud Anchor между устройствами не используется серверная часть Firebase, его гораздо проще приступить к работе. -
cloud_anchor_java
— это реализация многопользовательского варианта использования. Он использует ключ API для авторизации вызовов API ARCore.
Предварительные условия
Требования
Аппаратное обеспечение
Программное обеспечение
- Android Studio версии 3.0 или более поздней версии с платформой Android SDK версии 7.0 (уровень API 24) или более поздней версии.
- ARCore SDK для Android, который можно получить одним из двух способов:
- Загрузите его с GitHub и распакуйте на свой компьютер.
- Клонируйте репозиторий с помощью следующей команды:
git clone https://github.com/google-ar/arcore-android-sdk.git
Откройте пример приложения в Android Studio.
ARCore SDK предоставляет примеры приложений cloud_anchor_java
и persistent_cloud_anchor_java
для демонстрации функциональности Cloud Anchor. Выполните следующие действия, чтобы открыть приложения в Android Studio.
Постоянные облачные якоря
В Android Studio нажмите «Открыть» .
Перейдите в место, где на вашем компьютере хранится каталог arcore-android-sdk . Не открывайте всю папку SDK. Вместо этого перейдите в раздел Samples > persist_cloud_anchor_java и нажмите «Открыть» .
Облачные якоря
В Android Studio нажмите «Открыть» .
Перейдите в место, где на вашем компьютере хранится каталог arcore-android-sdk . Не открывайте всю папку SDK. Вместо этого перейдите в раздел Samples > cloud_anchor_java и нажмите Open .
Настройте общий доступ к идентификатору Cloud Anchor
Идентификаторы облачных привязок — это строки, которые идентифицируют размещенные облачные привязки. Они используются для разрешения или рендеринга 3D-объектов, прикрепленных к размещенным привязкам.
Постоянные облачные якоря
Совместное использование идентификатора Cloud Anchor поддерживается локально в приложении. Здесь вам не нужно будет ничего делать.
Облачные якоря
Пример приложения cloud_anchor_java
использует базы данных Firebase Realtime для обмена идентификаторами Cloud Anchor между устройствами. Вы можете использовать другое решение в своих приложениях.
- Добавьте Firebase в свое приложение вручную. Имя пакета
cloud_anchor_java
— com.google.ar.core.examples.java.cloudanchor
. Вы можете найти его в main/AndroidManifest.xml
. - Загрузите файл
google-services.json
, который вы создали при добавлении Firebase в свое приложение. - Создайте базу данных реального времени с помощью Firebase.
- В Android Studio добавьте файл
google-services.json
в каталог app
вашего проекта.
Авторизация вызовов API ARCore
Авторизуйте вызовы API ARCore для размещения и разрешения облачных привязок для вашего приложения. Выполните инструкции по использованию API ARCore в Google Cloud и используйте авторизацию без ключа для постоянных облачных привязок или авторизацию по ключу API для облачных привязок.
Создайте и запустите пример приложения.
Постоянные облачные якоря
Запустите приложение
- Убедитесь, что на вашем устройстве включены параметры разработчика и отладка по USB .
- Подключите свое устройство через USB к машине разработки.
- В Android Studio выберите свое устройство в качестве цели развертывания и нажмите «Выполнить» .
persistent_cloud_anchor_java
должен запуститься на вашем устройстве, предлагая ARCore обнаружить самолеты перед камерой устройства.
Если авторизация в Google Cloud не удалась, см. раздел Действия по устранению неполадок .
Поместите якорь
- Как только приложение начнет обнаруживать самолеты, коснитесь экрана, чтобы привязать якорь к одному из обнаруженных самолетов.
- Нажмите кнопку HOST , чтобы разместить размещенный якорь. При этом к API ARCore отправляется запрос хоста, который включает данные, представляющие положение привязки относительно визуальных объектов рядом с ней.
Успешный запрос хоста устанавливает привязку в размещенном месте и присваивает ей идентификатор облачной привязки. Если запрос хоста успешен, приложение должно отобразить код комнаты. Вы можете использовать этот код для доступа к ранее размещенным привязкам для этой комнаты на любом устройстве.
Разрешить якорь
- Нажмите «РАЗРЕШИТЬ» и введите ранее возвращенный код комнаты, чтобы получить доступ к якорям, размещенным в этой комнате. При этом запрос на разрешение отправляется в API ARCore, который возвращает идентификаторы всех якорей, размещенных в данный момент в комнате.
persistent_cloud_anchor_java
будет использовать эти идентификаторы для рендеринга 3D-объектов, прикрепленных к размещенным привязкам.
Облачные якоря
Запустите приложение
- Убедитесь, что на вашем устройстве включены параметры разработчика и отладка по USB .
- Подключите устройство через USB к машине разработки.
- В Android Studio выберите свое устройство в качестве цели развертывания и нажмите «Выполнить» .
cloud_anchor_java
должен запуститься на вашем устройстве, предлагая ARCore обнаружить самолеты перед камерой устройства.
Ошибка: com.google.firebase.database.DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance
Если вы столкнулись с этой ошибкой, убедитесь, что свойство firebase_url
присутствует в google-services.json
. Вы можете получить правильное значение для этого свойства, убедившись, что база данных реального времени создана, и загрузив google-services.json
.
Поместите якорь
- Как только приложение начнет обнаруживать самолеты, коснитесь экрана, чтобы привязать якорь к одному из обнаруженных самолетов.
- Нажмите кнопку HOST , чтобы разместить размещенный якорь. При этом к API ARCore отправляется запрос хоста, который включает данные, представляющие положение привязки относительно визуальных объектов рядом с ней.
Успешный запрос хоста устанавливает привязку в размещенном месте и присваивает ей идентификатор Cloud Anchors. Если запрос хоста успешен, приложение должно отобразить код комнаты. Вы можете использовать этот код для доступа к ранее размещенным привязкам для этой комнаты на любом устройстве.
Разрешить якорь
- Нажмите «РАЗРЕШИТЬ» и введите ранее возвращенный код комнаты, чтобы получить доступ к якорям, размещенным в этой комнате. При этом запрос на разрешение отправляется в API ARCore, который возвращает идентификаторы всех якорей, размещенных в данный момент в комнате.
cloud_anchor_java
будет использовать эти идентификаторы для рендеринга 3D-объектов, прикрепленных к размещенным привязкам.
Что дальше
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-25 UTC.
[null,null,["Последнее обновление: 2025-07-25 UTC."],[[["\u003cp\u003eExplore Cloud Anchors functionality using the \u003ccode\u003ecloud_anchor_java\u003c/code\u003e and \u003ccode\u003epersistent_cloud_anchor_java\u003c/code\u003e sample apps within the ARCore SDK.\u003c/p\u003e\n"],["\u003cp\u003ePersistent Cloud Anchors enable collaborative projects and persist for over 24 hours, while standard Cloud Anchors support multi-player use cases.\u003c/p\u003e\n"],["\u003cp\u003eBefore running the apps, ensure you have the necessary hardware and software, including an ARCore-supported device and Android Studio.\u003c/p\u003e\n"],["\u003cp\u003eAuthorize ARCore API calls using keyless authorization for Persistent Cloud Anchors and API key authorization for Cloud Anchors.\u003c/p\u003e\n"],["\u003cp\u003eHost and resolve anchors within the sample apps to experience Cloud Anchor functionality, placing and rendering 3D objects in shared AR experiences.\u003c/p\u003e\n"]]],["The content guides users to experiment with Cloud Anchors using two sample apps: `cloud_anchor_java` and `persistent_cloud_anchor_java`. These apps demonstrate hosting and resolving anchors via the ARCore API. Key actions include: installing prerequisites, opening the sample app in Android Studio, setting up Cloud Anchor ID sharing (using either keyless authorization or API key authorization), running the app, placing and hosting an anchor, and resolving an anchor using a room code. `Persistent_cloud_anchor_java` uses keyless authorization and local ID sharing. `cloud_anchor_java` uses API key authorization and Firebase for ID sharing.\n"],null,["# Cloud Anchors quickstart for Android\n\nTry out hosting and resolving [Cloud Anchors](/ar/develop/java/cloud-anchors/introduction) in the `cloud_anchor_java` and `persistent_cloud_anchor_java` sample apps.\n\nWhich sample app should you use?\n--------------------------------\n\nCloud Anchors are [anchors](/ar/develop/java/anchors) that are hosted on the [**ARCore API**](https://console.cloud.google.com/apis/library/arcore) cloud endpoint. This API enables users to share experiences in the same app. **Persistent Cloud Anchors** are Cloud Anchors that can be hosted for more than 24 hours.\n\n- `persistent_cloud_anchor_java` is an implementation of a collaborative project use case. It uses keyless authorization to authorize ARCore API calls. Because it doesn't use a Firebase backend to share Cloud Anchor IDs between devices, it is much easier to get up and running.\n- `cloud_anchor_java` is an implementation of a multi-player use case. It uses an API key to authorize ARCore API calls.\n\nPrerequisites\n-------------\n\n- Understand how [anchors](/ar/develop/java/anchors) and [Cloud Anchors](/ar/develop/java/cloud-anchors/introduction) work.\n- [Install and configure](/ar/develop/java/quickstart) the ARCore SDK for Android.\n\nRequirements\n------------\n\n### Hardware\n\n- An [ARCore supported device](/ar/devices) with the latest version of [Google Play Services for AR](https://play.google.com/store/apps/details?id=com.google.ar.core) installed\n- A USB cable to connect the device to your development machine\n\n### Software\n\n- [Android Studio](https://developer.android.com/studio) version 3.0 or later with Android SDK Platform version 7.0 (API level 24) or higher\n- The ARCore SDK for Android, which you can get in one of two ways:\n - Download it from [GitHub](https://github.com/google-ar/arcore-android-sdk) and extract it on your machine\n - Clone the repository with the following command: \n\n ```\n git clone https://github.com/google-ar/arcore-android-sdk.git\n ```\n\nOpen the sample app in Android Studio\n-------------------------------------\n\nThe ARCore SDK provides the `cloud_anchor_java` and `persistent_cloud_anchor_java` sample apps to demonstrate Cloud Anchors functionality. Follow these steps to open the apps in Android Studio. \n\n### Persistent Cloud Anchors\n\n1. In Android Studio, click **Open**.\n\n2. Navigate to the place where the **arcore-android-sdk** directory is stored on your machine. Do not open the entire SDK folder. Instead, go to **samples** \\\u003e **persistent_cloud_anchor_java** and click **Open**.\n\n### Cloud Anchors\n\n1. In Android Studio, click **Open**.\n\n2. Navigate to the place where the **arcore-android-sdk** directory is stored on your machine. Do not open the entire SDK folder. Instead, go to **samples** \\\u003e **cloud_anchor_java** and click **Open**.\n\nSet up Cloud Anchor ID sharing\n------------------------------\n\n**Cloud Anchor IDs** are strings that identify hosted Cloud Anchors. They are used to resolve, or render the 3D objects attached to, the hosted anchors. \n\n### Persistent Cloud Anchors\n\nCloud Anchor ID sharing is maintained locally in the app. You won't need to do anything here.\n\n### Cloud Anchors\n\nThe `cloud_anchor_java` sample app uses Firebase's Realtime Databases to share Cloud Anchor IDs between devices. You can use a different solution in your own apps.\n\n1. [Manually add Firebase to your app.](https://firebase.google.com/docs/android/setup#manually_add_firebase) The `cloud_anchor_java` package name is `com.google.ar.core.examples.java.cloudanchor`. You can find it in `main/AndroidManifest.xml`.\n2. Download the `google-services.json` file that you generated when you added Firebase to your app.\n3. [Create a Realtime Database with Firebase.](https://firebase.google.com/docs/database/android/start#create_a_database)\n4. In Android Studio, add the `google-services.json` file to your project's `app` directory.\n\nAuthorize ARCore API calls\n--------------------------\n\nAuthorize calls to the ARCore API to host and resolve Cloud Anchors for your\napp. Follow steps for on [Use the ARCore API on Google\nCloud](/ar/develop/authorization?platform=android) and use **Keyless\nauthorization** for Persistent Cloud Anchors or **API Key authorization** for\nCloud Anchors.\n\nBuild and run the sample app\n----------------------------\n\n### Persistent Cloud Anchors\n\n### Run the app\n\n1. Make sure that your device has enabled [developer options and USB debugging](https://developer.android.com/studio/debug/dev-options).\n2. Connect your device via USB to your development machine.\n3. In Android Studio, select your device as the deployment target and click **Run**.\n\n`persistent_cloud_anchor_java` should launch on your device, prompting ARCore to detect the planes in front of the device's camera.\n\nIf Google Cloud authorization fails, see [Troubleshooting steps](/ar/develop/authorization/troubleshooting?platform=android).\n\n### Place an anchor\n\n1. Once the app begins to detect planes, tap your screen to place an anchor on one of the detected planes.\n2. Tap the **HOST** button to host the placed anchor. This sends a host request to the ARCore API, which includes data representing the anchor's position relative to the visual features near it.\n\nA successful host request establishes an anchor at the placed location and assigns it a Cloud Anchor ID. If the host request is successful, the app should display a room code. You can use this code to access previously hosted anchors for this room on any device.\n\n### Resolve an anchor\n\n1. Tap **RESOLVE** and enter a previously returned room code to access the anchors hosted in this room. This sends a resolve request to the ARCore API, which returns the IDs of all anchors currently hosted in the room. `persistent_cloud_anchor_java` will use these IDs to render 3D objects attached to the hosted anchors.\n\n### Cloud Anchors\n\n### Run the app\n\n1. Make sure that your device has enabled [developer options and USB debugging](https://developer.android.com/studio/debug/dev-options).\n2. Connect your device via USB to your development machine.\n3. In Android Studio, select your device as the deployment target and click **Run**.\n\n`cloud_anchor_java` should launch on your device, prompting ARCore to detect the planes in front of the device's camera. \n\n#### Error: `com.google.firebase.database.DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance`\n\nIf you encounter this error, ensure that the `firebase_url` property is present in `google-services.json`. You can obtain the correct value for this property by ensuring that the Realtime Database has been created and downloading `google-services.json`.\n\n*** ** * ** ***\n\n### Place an anchor\n\n1. Once the app begins to detect planes, tap your screen to place an anchor on one of the detected planes.\n2. Tap the **HOST** button to host the placed anchor. This sends a host request to the ARCore API, which includes data representing the anchor's position relative to the visual features near it.\n\nA successful host request establishes an anchor at the placed location and assigns it a Cloud Anchors ID. If the host request is successful, the app should display a room code. You can use this code to access previously hosted anchors for this room on any device.\n\n### Resolve an anchor\n\n1. Tap **RESOLVE** and enter a previously returned room code to access the anchors hosted in this room. This sends a resolve request to the ARCore API, which returns the IDs of all anchors currently hosted in the room. `cloud_anchor_java` will use these IDs to render 3D objects attached to the hosted anchors.\n\nWhat's next\n-----------\n\n- Create a Cloud Anchors app with the [ARCore Cloud Anchors with persistent Cloud Anchors codelab](https://codelabs.developers.google.com/codelabs/arcore-cloud-anchors#0).\n- Learn how to incorporate Cloud Anchors in your app with the [Cloud Anchors developer guide](/ar/develop/java/cloud-anchors/developer-guide).\n- Manage Cloud Anchors outside of your ARCore app using the [Cloud Anchors Management API](/ar/develop/java/cloud-anchors/management-api)."]]