基于 Rokid AR 眼镜的 Android 喝水提醒应用开发
一款基于 Rokid AR 眼镜和 Android 开发的喝水提醒应用。针对程序员久坐少动的问题,利用 AR 眼镜视野可见的优势实现非中断式提醒。技术选型采用 CXR-M SDK,使用 Kotlin 构建数据层、前台服务及 SDK 封装。解决了蓝牙权限动态申请、提词器场景控制、中文编码及 TTS 播放完整性等关键问题。最终实现了定时提醒、数据记录及语音播报功能,为 AR 眼镜在健康管理类应用提供了实践参考。

一款基于 Rokid AR 眼镜和 Android 开发的喝水提醒应用。针对程序员久坐少动的问题,利用 AR 眼镜视野可见的优势实现非中断式提醒。技术选型采用 CXR-M SDK,使用 Kotlin 构建数据层、前台服务及 SDK 封装。解决了蓝牙权限动态申请、提词器场景控制、中文编码及 TTS 播放完整性等关键问题。最终实现了定时提醒、数据记录及语音播报功能,为 AR 眼镜在健康管理类应用提供了实践参考。

去年年底公司组织体检,拿到报告的时候我愣住了——尿酸偏高、肾结石早期征兆、血液粘稠度异常。医生问了我几个问题,最后归结为一句话:'你是不是经常一坐就是一整天,基本不怎么喝水?'
被说中了。作为一名程序员,写代码的时候经常进入'心流'状态,一坐就是三四个小时,等反应过来的时候,嗓子已经干得冒烟了。
买了各种喝水提醒 App,用过一段时间后都卸载了。原因很简单:
手机震动提醒的时候,我正在敲代码,下意识就把通知划掉了。
划掉之后呢?继续写代码。等想起来喝水这件事,已经是两小时后了。
这个场景让我开始思考:如果提醒不是出现在手机上,而是出现在我的视野里呢?
恰好看到 Rokid 开发者社区的征文活动,手里正好有一副 Rokid AR 眼镜。于是决定花一周时间,开发一款「喝水提醒助手」。
在做技术选型之前,我先分析了一下现有方案的痛点:
手机通知的问题:
智能水杯的问题:
Apple Watch / 手环的问题:
而 AR 眼镜有几个独特优势:
当然,AR 眼镜也有局限性——不是每个人都有,戴着不舒服,续航有限。但如果你恰好有一副,那这个方案值得一试。
Rokid 提供了两套开发方案:
| 方案 | 适用场景 | 学习成本 |
|---|---|---|
| 灵珠 AI 平台 | 对话式应用,需要 AI 生成内容 | 低,可视化配置 |
| CXR-M SDK | 纯代码开发,完全自定义 | 中,需要 Android 开发经验 |
我的需求很明确:
这些功能用 CXR-M SDK 完全能实现,而且不需要依赖云端服务。更重要的是,CXR-M SDK 内置了「提词器场景」(WORD_TIPS),正好可以用来显示喝水提醒。
所谓「提词器场景」,原本是给演讲者看稿子用的。但换个思路,把喝水提醒当'稿子'发过去,不就是我要的功能吗?
在动手写代码之前,我先规划了整体架构:

核心组件:
首先是 app/build.gradle.kts:
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.rokid.waterreminder"
compileSdk = 34
defaultConfig {
applicationId = "com.rokid.waterreminder"
minSdk = 28 // CXR-M SDK 要求最低 Android 9.0
targetSdk = 34
versionCode = 1
versionName = "1.0.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
// CXR-M SDK(核心依赖)
implementation("com.rokid.cxr:client-m:1.0.1-20250812.080117-2")
// SDK 需要的第三方库
implementation("com.squareup.okhttp3:okhttp:4.9.3")
implementation("com.google.code.gson:gson:2.10.1")
// AndroidX
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
}
这里有个坑:minSdk 必须设为 28 以上,否则编译会报错。我一开始设的是 21,折腾了半天才发现是 SDK 的硬性要求。

AndroidManifest.xml 中需要声明以下权限:
<!-- 蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<!-- 前台服务权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH" />
<!-- 通知权限(Android 13+) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
重点说一下 BLUETOOTH_SCAN 的 neverForLocation 标志。Android 系统规定蓝牙扫描需要定位权限,但这个标志可以告诉系统'我不是用来定位的'。这样用户在授权的时候,不会看到'此应用需要获取您的位置信息'这种吓人的提示。
另外,Android 12+ 和 Android 13+ 的蓝牙权限、通知权限都需要运行时动态申请,光在 Manifest 里声明是没用的。
先定义三个核心数据类:

// WaterRecord.kt
/**
* 单次喝水记录
*/
data class WaterRecord(
val id: Long = System.currentTimeMillis(), // 用时间戳作为唯一标识
val timestamp: Long = System.currentTimeMillis(),
val amountMl: Int, // 喝水量(毫升)
val note: String? = null // 备注(可选)
) {
fun getFormattedTime(): String {
val sdf = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault())
return sdf.format(java.util.Date(timestamp))
}
}
/**
* 每日喝水统计
*/
data class DailyStats(
val date: String, // 日期 yyyy-MM-dd
val totalMl: Int, // 总饮水量
val targetMl: Int, // 目标饮水量
val cupCount: Int // 喝水次数
) {
// 完成率(0.0 ~ 1.0+)
val completionRate: Float
get() = if (targetMl > 0) totalMl.toFloat() / targetMl else 0f
// 是否达标
val isGoalMet: Boolean
get() = totalMl >= targetMl
}
(
isEnabled: = ,
targetMl: = ,
cupSizeMl: = ,
intervalMinutes: = ,
startTime: String = ,
endTime: String = ,
glassesEnabled: = ,
ttsEnabled: =
) {
{
DEFAULT = ReminderSettings()
}
}
这里用 data class 是因为 Kotlin 会自动生成 equals()、hashCode()、copy() 等方法,非常方便。copy() 方法在修改设置时特别好用:
// 修改单个字段
val newSettings = settings.copy(targetMl = 3000)
// 修改多个字段
val newSettings = settings.copy(
targetMl = 3000,
intervalMinutes = 45
)
数据存储用的是 SharedPreferences + Gson。为什么不 SQLite/Room?因为这个应用的数据量很小,一天最多几十条记录,用 SharedPreferences 完全够用,而且代码更简单。

// WaterRepository.kt
class WaterRepository private constructor(context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
private val gson = Gson()
companion object {
private const val PREFS_NAME = "water_reminder_prefs"
private const val KEY_RECORDS = "water_records"
private const val KEY_SETTINGS = "reminder_settings"
@Volatile
private var instance: WaterRepository? = null
fun getInstance(context: Context): WaterRepository {
return instance ?: synchronized(this) {
instance ?: WaterRepository(context.applicationContext).also {
instance = it
}
}
}
}
// 添加喝水记录
fun addRecord(record: WaterRecord) {
val records = getAllRecords().toMutableList()
records.add(0, record) // 新记录插入到开头
saveRecords(records)
}
// 获取今日记录
fun getTodayRecords: List<WaterRecord> {
today = getTodayDateString()
getAllRecords().filter { record -> getDateString(record.timestamp) == today }
}
: DailyStats {
todayRecords = getTodayRecords()
settings = getSettings()
DailyStats(
date = getTodayDateString(),
totalMl = todayRecords.sumOf { it.amountMl },
targetMl = settings.targetMl,
cupCount = todayRecords.size
)
}
: List<DailyStats> {
settings = getSettings()
records = getAllRecords()
result = mutableListOf<DailyStats>()
calendar = java.util.Calendar.getInstance()
(i until days) {
date = java.text.SimpleDateFormat(, java.util.Locale.getDefault()).format(calendar.time)
dayRecords = records.filter { getDateString(it.timestamp) == date }
result.add(DailyStats(
date = date,
totalMl = dayRecords.sumOf { it.amountMl },
targetMl = settings.targetMl,
cupCount = dayRecords.size
))
calendar.add(java.util.Calendar.DAY_OF_MONTH, -)
}
result.reversed()
}
: ReminderSettings {
json = prefs.getString(KEY_SETTINGS, ) ?: ReminderSettings.DEFAULT
{
gson.fromJson(json, ReminderSettings::.java)
} (e: Exception) {
ReminderSettings.DEFAULT
}
}
{
prefs.edit().putString(KEY_SETTINGS, gson.toJson(settings)).apply()
}
}
这里用单例模式来管理 Repository 实例,避免重复创建。@Volatile + synchronized 是为了保证线程安全。
这是整个项目的核心。CXR-M SDK 的 API 虽然不复杂,但有一些细节需要注意。我把它封装成了一个单例类:

// RokidGlassesManager.kt
object RokidGlassesManager {
private const val TAG = "RokidGlassesManager"
private val cxrApi: CxrApi by lazy { CxrApi.getInstance() }
private var connectionCallback: ConnectionCallback? = null
// ========== 回调接口 ==========
interface ConnectionCallback {
fun onConnecting()
fun onConnected()
fun onDisconnected()
fun onFailed(errorMsg: String)
}
interface SendCallback {
fun onSuccess()
fun onFailed(errorMsg: String)
}
// ========== 连接相关 ==========
val isConnected: Boolean
get() = cxrApi.isBluetoothConnected
fun setConnectionCallback(callback: ConnectionCallback?) {
this.connectionCallback = callback
}
: BluetoothDevice? {
(ActivityCompat.checkSelfPermission(
bluetoothAdapter.javaClass,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {
}
bondedDevices = bluetoothAdapter.bondedDevices
(device bondedDevices) {
deviceName = device.name ?:
(deviceName.contains(, ignoreCase = ) || deviceName.contains(, ignoreCase = )) {
Log.d(TAG, )
device
}
}
}
{
Log.d(TAG, )
connectionCallback?.onConnecting()
cxrApi.initBluetooth(
context = context,
device = device,
callback = : BluetoothStatusCallback() {
{
Log.d(TAG, )
(!socketUuid.isNullOrEmpty() && !macAddress.isNullOrEmpty()) {
connectBluetooth(context, socketUuid, macAddress)
} {
connectionCallback?.onFailed()
}
}
{
Log.d(TAG, )
connectionCallback?.onConnected()
}
{
Log.w(TAG, )
connectionCallback?.onDisconnected()
}
{
errorMsg = getBluetoothErrorMessage(errorCode)
Log.e(TAG, )
connectionCallback?.onFailed(errorMsg)
}
}
)
}
{
cxrApi.connectBluetooth(
context = context,
socketUuid = socketUuid,
macAddress = macAddress,
callback = : BluetoothStatusCallback() {
{
Log.d(TAG, )
}
{
connectionCallback?.onDisconnected()
}
{
connectionCallback?.onFailed(getBluetoothErrorMessage(errorCode))
}
{
}
}
)
}
}
这里有一个关键细节:连接眼镜分两步:
initBluetooth() 获取连接信息(UUID 和 MAC 地址)onConnectionInfo 回调中拿到信息后,调用 connectBluetooth() 建立真正的连接我一开始以为调用 initBluetooth() 就能连上,结果等了半天没反应。后来看文档才发现需要两步。
/**
* 发送喝水提醒到眼镜
*/
fun sendWaterReminder(text: String, callback: SendCallback? = null): Boolean {
if (!isConnected) {
callback?.onFailed("眼镜未连接")
return false
}
// 关键:必须先打开提词器场景!
cxrApi.controlScene(
sceneType = ValueUtil.CxrSceneType.WORD_TIPS,
openOrClose = true,
otherParams = null
)
Log.d(TAG, "发送喝水提醒,长度:${text.length}")
val status = cxrApi.sendStream(
type = ValueUtil.CxrStreamType.WORD_TIPS,
stream = text.toByteArray(Charsets.UTF_8), // 重要:必须指定 UTF-8 编码
fileName = "water_reminder.txt",
cb = object : SendStatusCallback() {
override fun onSendSucceed() {
Log.d(TAG, "喝水提醒发送成功")
callback?.onSuccess()
}
override fun onSendFailed(errorCode: ValueUtil.CxrSendErrorCode?) {
val errorMsg = getSendErrorMessage(errorCode)
Log.e(TAG, "喝水提醒发送失败:$errorMsg")
callback?.onFailed(errorMsg)
}
}
)
return status == ValueUtil.CxrStatus.REQUEST_SUCCEED
}
又一个坑:发送数据之前,必须先调用 controlScene() 打开提词器场景。我一开始直接调用 sendStream(),眼镜端什么反应都没有。折腾了半天才发现这个问题。
另外,必须指定 UTF-8 编码,否则中文会变成乱码:
// 错误写法(中文会乱码)
stream = text.toByteArray()
// 正确写法
stream = text.toByteArray(Charsets.UTF_8)
/**
* 发送 TTS 语音播报
*/
fun sendTts(text: String): Boolean {
if (!isConnected) {
return false
}
Log.d(TAG, "发送 TTS: $text")
val status = cxrApi.sendTtsContent(text)
if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
// 重要:通知 SDK TTS 播放完成
cxrApi.notifyTtsAudioFinished()
return true
}
return false
}
TTS 播放后要调用 notifyTtsAudioFinished(),否则可能出现播放不完整的情况。
Android 8.0+ 对后台服务限制很严格,普通后台服务很快就会被系统杀掉。所以必须使用前台服务,显示一个常驻通知。
// ReminderService.kt
class ReminderService : Service() {
companion object {
private const val TAG = "ReminderService"
private const val CHANNEL_ID = "water_reminder_channel"
private const val NOTIFICATION_ID = 1001
const val ACTION_START = "com.rokid.waterreminder.ACTION_START"
const val ACTION_STOP = "com.rokid.waterreminder.ACTION_STOP"
fun start(context: Context) {
val intent = Intent(context, ReminderService::class.java).apply {
action = ACTION_START
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
fun stop(context: Context) {
val intent = Intent(context, ReminderService::class.java).apply {
action = ACTION_STOP
}
context.startService(intent)
}
}
private val serviceScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private var reminderJob: Job? =
repository: WaterRepository
lastReminderTime: =
{
.onCreate()
repository = WaterRepository.getInstance(applicationContext)
createNotificationChannel()
Log.d(TAG, )
}
: {
(intent?.action) {
ACTION_START -> startReminder()
ACTION_STOP -> stopSelf()
}
START_STICKY
}
{
startForeground(NOTIFICATION_ID, createNotification())
reminderJob = serviceScope.launch {
(isActive) {
checkAndRemind()
delay( * )
}
}
Log.d(TAG, )
}
{
settings = repository.getSettings()
(!settings.isEnabled)
(!isInReminderTime(settings.startTime, settings.endTime))
todayStats = repository.getTodayStats()
(todayStats.isGoalMet)
now = System.currentTimeMillis()
intervalMs = settings.intervalMinutes * *
(now - lastReminderTime < intervalMs)
sendReminder(settings, todayStats)
lastReminderTime = now
}
{
remainingMl = settings.targetMl - stats.totalMl
remainingCups = (remainingMl + settings.cupSizeMl - ) / settings.cupSizeMl
tips = listOf(, , , )
message =
showNotification(message)
(settings.glassesEnabled && RokidGlassesManager.isConnected) {
RokidGlassesManager.sendWaterReminder(message)
}
(settings.ttsEnabled && RokidGlassesManager.isConnected) {
RokidGlassesManager.sendTts()
}
Log.d(TAG, )
}
}
这里用 Kotlin 协程来处理定时任务,比传统的 Handler + Runnable 更简洁。
服务保活策略:
START_STICKY:服务被杀后自动重启主界面使用 ViewBinding 来访问视图,配合协程处理数据加载:
// MainActivity.kt
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "MainActivity"
private const val REQUEST_PERMISSIONS = 1001
}
private lateinit var binding: ActivityMainBinding
private lateinit var repository: WaterRepository
private var settings = ReminderSettings.DEFAULT
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
repository = WaterRepository.getInstance(this)
settings = repository.getSettings()
setupViews()
checkPermissions()
observeConnection()
// 启动提醒服务
if (settings.isEnabled) {
ReminderService.start(this)
}
}
private fun setupViews() {
updateTodayStats()
// 快速喝水按钮
binding.btnDrink.setOnClickListener {
addWaterRecord(settings.cupSizeMl)
}
// 自定义喝水量
binding.btnCustomDrink.setOnClickListener {
showCustomDrinkDialog()
}
// 眼镜连接
binding.btnConnectGlasses.setOnClickListener {
if (RokidGlassesManager.isConnected) {
RokidGlassesManager.disconnect()
} {
connectGlasses()
}
}
binding.btnTestReminder.setOnClickListener {
sendTestReminder()
}
}
{
lifecycleScope.launch {
stats = repository.getTodayStats()
binding.apply {
tvTotalMl.text =
tvCupCount.text =
tvTargetMl.text =
progressWater.progress = (stats.completionRate * ).toInt().coerceAtMost()
(stats.isGoalMet) {
tvStatus.text =
tvStatus.setTextColor(getColor(R.color.success))
} {
remaining = stats.targetMl - stats.totalMl
tvStatus.text =
tvStatus.setTextColor(getColor(R.color.text_secondary))
}
}
}
}
{
record = WaterRecord(amountMl = amountMl)
repository.addRecord(record)
updateTodayStats()
binding.root.performHapticFeedback(android.view.HapticFeedbackConstants.CONFIRM)
Toast.makeText(, , Toast.LENGTH_SHORT).show()
(RokidGlassesManager.isConnected && settings.glassesEnabled) {
stats = repository.getTodayStats()
message =
RokidGlassesManager.sendWaterReminder(message)
}
}
{
RokidGlassesManager.setConnectionCallback( : RokidGlassesManager.ConnectionCallback {
{
runOnUiThread {
binding.btnConnectGlasses.text =
}
}
{
runOnUiThread {
updateConnectionStatus()
Toast.makeText(, , Toast.LENGTH_SHORT).show()
}
}
{
runOnUiThread {
updateConnectionStatus()
}
}
{
runOnUiThread {
updateConnectionStatus()
Toast.makeText(, , Toast.LENGTH_SHORT).show()
}
}
})
}
}
界面布局用了 Material Design 风格的卡片式设计,主要分三个区域:
Android 12 (API 31) 新增了 BLUETOOTH_SCAN 和 BLUETOOTH_CONNECT 权限,而且必须运行时申请。
我一开始只在 Manifest 里声明了权限,Debug 版能跑,Release 版直接崩溃。排查了半天才发现是权限问题。
解决方案:
private fun checkPermissions() {
val permissions = mutableListOf<String>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
permissions.add(Manifest.permission.BLUETOOTH_SCAN)
permissions.add(Manifest.permission.BLUETOOTH_CONNECT)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
permissions.add(Manifest.permission.POST_NOTIFICATIONS)
}
val notGranted = permissions.filter {
ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
}
if (notGranted.isNotEmpty()) {
ActivityCompat.requestPermissions(this, notGranted.toTypedArray(), REQUEST_PERMISSIONS)
}
}
sendStream() 调用成功,返回值也是 REQUEST_SUCCEED,但眼镜端什么都没显示。
原因:没有先调用 controlScene() 打开场景。
解决方案:
// 必须先打开场景
cxrApi.controlScene(ValueUtil.CxrSceneType.WORD_TIPS, true, null)
// 然后发送数据
cxrApi.sendStream(ValueUtil.CxrStreamType.WORD_TIPS, data, fileName, callback)
第一次发送中文到眼镜,显示的是乱码。
原因:没有指定编码,使用了系统默认编码。
解决方案:
stream = text.toByteArray(Charsets.UTF_8)
有时候 TTS 只播了一半就停了。
原因:没有调用 notifyTtsAudioFinished() 通知 SDK。
解决方案:
val status = cxrApi.sendTtsContent(text)
if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
cxrApi.notifyTtsAudioFinished() // 必须调用
}
经过一周的开发和调试,应用终于能正常运行了。
功能清单:
| 功能 | 说明 |
|---|---|
| 喝水记录 | 一键记录 + 自定义数量 |
| 目标追踪 | 进度条实时显示 |
| 定时提醒 | 前台服务保活 |
| 眼镜同步 | 提词器场景显示 |
| TTS 播报 | 语音提醒 |
| 历史统计 | 近 7 天数据 |
眼镜端显示效果:

做这个项目的过程中,我一直在思考这个问题。
AR 眼镜的优势是信息即视性——不需要主动去看,信息就在视野里。但这同时是劣势:屏幕小、分辨率有限、长时间佩戴不舒服。
所以,AR 眼镜最适合的场景是:
不适合的场景:
如果继续完善这个项目,我会考虑:
这个项目虽然简单,但确实解决了我的实际问题。现在每天都能完成 2000ml 的饮水目标,上次复查指标也有所改善。
开发过程中踩了不少坑,但也让我对 CXR-M SDK 有了更深入的理解。希望这篇文章能帮到其他想用 Rokid 眼镜做应用的开发者。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online