Android Studio 中配置 ARCore 开发环境
前提条件
- Android Studio Arctic Fox(2020.3.1)或更高版本
- JDK 11 或更高(Android Studio 自带)
- Gradle 插件 4.1.0+
- 物理 Android 测试设备(模拟器调试见后文,功能有限)
步骤一:新建或打开项目
新建项目时选择 Empty Activity 模板,Kotlin 语言,最低 API 级别选 24 (Nougat) 或更高——这是 ARCore 的最低要求。
如果在现有项目中集成,直接打开项目即可。
步骤二:添加 ARCore 依赖
在项目根目录的 build.gradle(或新版本 Gradle 的 settings.gradle)中,确保 Google 的 Maven 仓库在第一位:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google() // ARCore 依赖在这里
mavenCentral()
}
}
在 app 模块的 build.gradle 中,添加 Google Play Services for AR 的依赖:
dependencies {
// ARCore SDK
implementation 'com.google.ar:core:1.49.0'
// 可选:Sceneform 简化 3D 渲染(已废弃,建议用 OpenGL 或 Unity)
// implementation 'com.google.ar.sceneform:core:1.17.1'
}
版本号 1.49.0 请以 Google Maven Repository 上最新发布版本为准。
步骤三:配置 AndroidManifest.xml
在 AndroidManifest.xml 中添加摄像头权限声明和 ARCore 元数据:
<!-- 摄像头权限:ARCore 必须 -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- OpenGL ES 3.0:ARCore 渲染依赖 -->
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
<!-- 可选:声明你的应用是 ARCore 应用,让不支持的设备在 Play 商店里看不到 -->
<uses-feature android:name="com.google.ar.core" android:required="true" />
在 <application> 标签内添加 ARCore 元数据声明:
<meta-data
android:name="com.google.ar.core"
android:value="optional" />
如果你的应用要求设备必须支持 ARCore(不支持就不允许安装),把 <uses-feature> 的 required 改为 true,meta-data 的 value 也改为 required。
步骤四:运行时检测与 Session 创建
ARCore Session 的创建是核心入口。典型的 Activity 骨架代码:
class ArActivity : AppCompatActivity() {
private var arSession: Session? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 检查设备是否支持 ARCore
val availability = ArCoreApk.getInstance().checkAvailability(this)
if (availability.isUnsupported) {
// 设备不支持,给用户提示后退出
finish()
return
}
}
override fun onResume() {
super.onResume()
// 确保 Google Play Services for AR 已安装
if (arSession == null) {
ArCoreApk.getInstance().requestInstall(this, true)
arSession = Session(this).apply {
configure(Session.Config(this))
}
}
arSession?.resume()
}
override fun onPause() {
super.onPause()
arSession?.pause()
}
}
关键点:
ArCoreApk.getInstance().checkAvailability()返回的状态决定了后续流程requestInstall()会在设备没有 Play Services for AR 时自动触发安装- Session 的生命周期与 Activity 对齐,
resume()/pause()必须配对调用
步骤五:设置 OpenGL 渲染环境
ARCore 不直接负责渲染,你需要自己用 OpenGL ES 或集成 Sceneform/Unity。基础步骤:
- 创建一个
GLSurfaceView作为 AR 画面的容器 - 在
Renderer的onDrawFrame回调中调用session.update()—— 这会获取最新的 camera pose - 将 ARCore 的 camera pose 传给你的 3D 渲染引擎,把虚拟物体叠加到摄像头画面上
Sceneform 已废弃:Google 在 2021 年宣布停止 Sceneform 的更新。新项目建议直接用 OpenGL/Vulkan,或者转向 Unity AR Foundation 做 3D 渲染。