Configurar uma sessão do ARCore no Android
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Configure uma sessão do ARCore para criar experiências de RA para seu app.
O que é uma sessão?
Todos os processos de RA, como rastreamento de movimento,
compreensão ambiental e estimativa de iluminação, acontecem dentro de um ARCore
sessão. Session
é o principal ponto de entrada para o ARCore
API. Ele gerencia o estado do sistema de RA e o ciclo de vida da sessão, permitindo
o aplicativo para criar, configurar, iniciar ou interromper uma sessão. O mais importante é que
permite que o app receba frames que permitem o acesso à imagem da câmera e
posição do dispositivo.
A sessão pode ser usada para configurar os seguintes recursos:
Verificar se o ARCore está instalado e atualizado
Antes de criar um Session
, verifique se o ARCore está instalado e atualizado. Se
O ARCore não está instalado, a criação da sessão falha e qualquer instalação subsequente
ou o upgrade do ARCore
exige a reinicialização do app.
Java
// Verify that ARCore is installed and using the current version.
private boolean isARCoreSupportedAndUpToDate() {
ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this);
switch (availability) {
case SUPPORTED_INSTALLED:
return true;
case SUPPORTED_APK_TOO_OLD:
case SUPPORTED_NOT_INSTALLED:
try {
// Request ARCore installation or update if needed.
ArCoreApk.InstallStatus installStatus = ArCoreApk.getInstance().requestInstall(this, true);
switch (installStatus) {
case INSTALL_REQUESTED:
Log.i(TAG, "ARCore installation requested.");
return false;
case INSTALLED:
return true;
}
} catch (UnavailableException e) {
Log.e(TAG, "ARCore not installed", e);
}
return false;
case UNSUPPORTED_DEVICE_NOT_CAPABLE:
// This device is not supported for AR.
return false;
case 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.
case UNKNOWN_ERROR:
case UNKNOWN_TIMED_OUT:
// There was an error checking for AR availability. This may be due to the device being offline.
// Handle the error appropriately.
}
}
Kotlin
// Verify that ARCore is installed and using the current version.
fun isARCoreSupportedAndUpToDate(): Boolean {
return when (ArCoreApk.getInstance().checkAvailability(this)) {
Availability.SUPPORTED_INSTALLED -> true
Availability.SUPPORTED_APK_TOO_OLD, Availability.SUPPORTED_NOT_INSTALLED -> {
try {
// Request ARCore installation or update if needed.
when (ArCoreApk.getInstance().requestInstall(this, true)) {
InstallStatus.INSTALL_REQUESTED -> {
Log.i(TAG, "ARCore installation requested.")
false
}
InstallStatus.INSTALLED -> true
}
} catch (e: UnavailableException) {
Log.e(TAG, "ARCore not installed", e)
false
}
}
Availability.UNSUPPORTED_DEVICE_NOT_CAPABLE ->
// This device is not supported for AR.
false
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.
}
Availability.UNKNOWN_ERROR, 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.
}
}
}
Criar uma sessão
Crie e configure uma sessão no ARCore.
Java
public void createSession() {
// Create a new ARCore session.
session = new Session(this);
// Create a session config.
Config config = new Config(session);
// Do feature-specific operations here, such as enabling depth or turning on
// support for Augmented Faces.
// Configure the session.
session.configure(config);
}
Kotlin
fun createSession() {
// Create a new ARCore session.
session = Session(this)
// Create a session config.
val config = Config(session)
// Do feature-specific operations here, such as enabling depth or turning on
// support for Augmented Faces.
// Configure the session.
session.configure(config)
}
Encerrar uma sessão
O Session
tem uma quantidade significativa de memória de heap nativa. A falha em explicitamente
fechar a sessão pode fazer com que o app fique sem memória nativa e falhe. Quando
a sessão de RA não for mais necessária, chame
close()
para lançar
do Google Cloud. Se o app tiver uma única atividade compatível com RA, chame close()
.
do método onDestroy()
da atividade.
Java
// Release native heap memory used by an ARCore session.
session.close();
Kotlin
// Release native heap memory used by an ARCore session.
session.close()
Próximas etapas
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-07-26 UTC.
[null,null,["Última atualização 2025-07-26 UTC."],[[["\u003cp\u003eARCore sessions manage all AR processes like motion tracking and environmental understanding, and are accessed via the \u003ccode\u003eSession\u003c/code\u003e object.\u003c/p\u003e\n"],["\u003cp\u003eBefore creating an ARCore session, ensure ARCore is installed and up-to-date on the device to prevent session creation failures.\u003c/p\u003e\n"],["\u003cp\u003eTo configure features like lighting estimation or cloud anchors, utilize the \u003ccode\u003eConfig\u003c/code\u003e object and apply it to the session.\u003c/p\u003e\n"],["\u003cp\u003eTo prevent memory leaks and crashes, explicitly close the session using \u003ccode\u003esession.close()\u003c/code\u003e when it's no longer needed, such as in the activity's \u003ccode\u003eonDestroy()\u003c/code\u003e method.\u003c/p\u003e\n"]]],[],null,["# Configure an ARCore session in Android\n\nConfigure an ARCore session to build AR experiences for your app.\n\nWhat is a session?\n------------------\n\nAll [AR processes](/ar/discover/concepts), such as motion tracking,\nenvironmental understanding, and lighting estimation, happen inside an ARCore\nsession. [`Session`](/ar/reference/java/com/google/ar/core/Session) is the main entry point to the ARCore\nAPI. It manages the AR system state and handles the session lifecycle, allowing\nthe app to create, configure, start, or stop a session. Most importantly, it\nenables the app to receive frames that allow access to the camera image and\ndevice pose.\n\nThe session can be used to configure the following features:\n\n- [Lighting Estimation](/ar/develop/lighting-estimation)\n- [Cloud Anchors](/ar/develop/cloud-anchors)\n- [Augmented Images](/ar/develop/augmented-images)\n- [Augmented Faces](/ar/develop/augmented-faces)\n- [Depth API](/ar/develop/depth)\n- [Instant Placement](/ar/develop/instant-placement)\n- [ARCore Geospatial API](/ar/develop/geospatial)\n\nVerify that ARCore is installed and up to date\n----------------------------------------------\n\nBefore creating a `Session`, verify that ARCore is installed and up to date. If\nARCore isn't installed, session creation fails and any subsequent installation\nor upgrade of ARCore requires an app restart. \n\n### Java\n\n // Verify that ARCore is installed and using the current version.\n private boolean isARCoreSupportedAndUpToDate() {\n ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this);\n switch (availability) {\n case SUPPORTED_INSTALLED:\n return true;\n\n case SUPPORTED_APK_TOO_OLD:\n case SUPPORTED_NOT_INSTALLED:\n try {\n // Request ARCore installation or update if needed.\n ArCoreApk.InstallStatus installStatus = ArCoreApk.getInstance().requestInstall(this, true);\n switch (installStatus) {\n case INSTALL_REQUESTED:\n Log.i(TAG, \"ARCore installation requested.\");\n return false;\n case INSTALLED:\n return true;\n }\n } catch (UnavailableException e) {\n Log.e(TAG, \"ARCore not installed\", e);\n }\n return false;\n\n case UNSUPPORTED_DEVICE_NOT_CAPABLE:\n // This device is not supported for AR.\n return false;\n\n case UNKNOWN_CHECKING:\n // ARCore is checking the availability with a remote query.\n // This function should be called again after waiting 200 ms to determine the query result.\n case UNKNOWN_ERROR:\n case UNKNOWN_TIMED_OUT:\n // There was an error checking for AR availability. This may be due to the device being offline.\n // Handle the error appropriately.\n }\n }\n\n### Kotlin\n\n // Verify that ARCore is installed and using the current version.\n fun isARCoreSupportedAndUpToDate(): Boolean {\n return when (ArCoreApk.getInstance().checkAvailability(this)) {\n Availability.SUPPORTED_INSTALLED -\u003e true\n Availability.SUPPORTED_APK_TOO_OLD, Availability.SUPPORTED_NOT_INSTALLED -\u003e {\n try {\n // Request ARCore installation or update if needed.\n when (ArCoreApk.getInstance().requestInstall(this, true)) {\n InstallStatus.INSTALL_REQUESTED -\u003e {\n Log.i(TAG, \"ARCore installation requested.\")\n false\n }\n InstallStatus.INSTALLED -\u003e true\n }\n } catch (e: UnavailableException) {\n Log.e(TAG, \"ARCore not installed\", e)\n false\n }\n }\n\n Availability.UNSUPPORTED_DEVICE_NOT_CAPABLE -\u003e\n // This device is not supported for AR.\n false\n\n Availability.UNKNOWN_CHECKING -\u003e {\n // ARCore is checking the availability with a remote query.\n // This function should be called again after waiting 200 ms to determine the query result.\n }\n Availability.UNKNOWN_ERROR, Availability.UNKNOWN_TIMED_OUT -\u003e {\n // There was an error checking for AR availability. This may be due to the device being offline.\n // Handle the error appropriately.\n }\n }\n }\n\nCreate a session\n----------------\n\nCreate and configure a session in ARCore. \n\n### Java\n\n public void createSession() {\n // Create a new ARCore session.\n session = new Session(this);\n\n // Create a session config.\n Config config = new Config(session);\n\n // Do feature-specific operations here, such as enabling depth or turning on\n // support for Augmented Faces.\n\n // Configure the session.\n session.configure(config);\n }\n\n### Kotlin\n\n fun createSession() {\n // Create a new ARCore session.\n session = Session(this)\n\n // Create a session config.\n val config = Config(session)\n\n // Do feature-specific operations here, such as enabling depth or turning on\n // support for Augmented Faces.\n\n // Configure the session.\n session.configure(config)\n }\n\nClose a session\n---------------\n\n`Session` owns a significant amount of native heap memory. Failure to explicitly\nclose the session may cause your app to run out of native memory and crash. When\nthe AR session is no longer needed, call\n[`close()`](/ar/reference/java/com/google/ar/core/Session#close()) to release\nresources. If your app contains a single AR-enabled activity, call `close()`\nfrom the activity's `onDestroy()` method. \n\n### Java\n\n // Release native heap memory used by an ARCore session.\n session.close();\n\n### Kotlin\n\n // Release native heap memory used by an ARCore session.\n session.close()\n\nNext steps\n----------\n\n- [ARCore quickstart for Android](/ar/develop/java/quickstart)"]]