Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(android): Android now tells you when a new version is out and updates from the browser

wquguru458324bafdb4
diff --git a/android/README.md b/android/README.md
index ea9a534..09a47e0 100644
--- a/android/README.md
+++ b/android/README.md
@@ -6,6 +6,7 @@ Cicada 的 Android 版:把手机里播放的声音(或面对面时麦克风
- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求返回语言、原文和译文;需要 Ling key。和 Windows 版同一套做法。
- 悬浮窗:纪要或字幕条,`FLAG_NOT_FOCUSABLE` 不抢输入,`FLAG_SECURE` 默认不出现在截图和录屏里;打开“共享屏幕时让对方看到”后显示“对方可见”。
- 纪要、记录格式(逐字节和 Mac 一致)、提示词、文案都和 Mac 版一致;英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Android 独有的在 `app/src/main/strings/`。
+- 检查更新:每天在后台查一次 GitHub Releases,有新版本时在首页、设置和通知里提示,点“更新”用浏览器下载 APK,由系统安装器覆盖安装(签名一致才行),不需要安装权限。
- 只用 Kotlin 标准库和 Android 框架,不用 AndroidX、Compose 或其他库。
## 目录
@@ -43,7 +44,7 @@ scripts/shot.sh # 截图:悬浮窗应是黑块;capture o
scripts/tap.sh "开始听" # 按屏幕上的文字点(系统对话框也行),用来走真实界面
```
-`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|onboarding、import)。只有开发版有,且只接受 adb。
+`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|onboarding、import、updatefeed、update check|download|job|notify)。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。
界面按 claude.ai 上的设计画布实现:首页、正在听、悬浮窗(纪要卡片 / 字幕条 / 小圆点)、三步引导、会议记录、会议详情、设置。文案用 Gemini(`google/gemini-4-argon`)审过一遍,与 Mac 共用的文案沿用 Mac 的译法。
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 7a48716..97293aa 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -11,6 +11,9 @@
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- The floating notes window / subtitle bar. -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+ <!-- The daily update check: waits for a network, and keeps its schedule across a restart. -->
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".CicadaApp"
@@ -53,6 +56,7 @@
<intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
</service>
+ <service android:name=".UpdateJob" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" />
<service android:name=".ListenService" android:exported="false"
android:foregroundServiceType="mediaProjection|microphone|dataSync" />
</application>
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index f92e4b6..af2343b 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -40,6 +40,7 @@ class CicadaApp : Application() {
lateinit var listen: ListenEngine
lateinit var overlay: Overlay
lateinit var voice: Voice
+ lateinit var updates: AppUpdates
val main = Handler(Looper.getMainLooper())
val background = Executors.newCachedThreadPool { r -> Thread(r, "App").apply { isDaemon = true } }
private val observers = LinkedHashSet<() -> Unit>()
@@ -50,6 +51,8 @@ class CicadaApp : Application() {
@Volatile var startProblem: String? = null
/// Cicada's own screens in front: the floating window is for other apps, so it waits.
private var resumed = 0
+ /// One of Cicada's screens is in front.
+ val foreground get() = resumed > 0
/// Android silenced our recording: a phone call, or another app holding the microphone.
@Volatile var micSilenced = false
/// The user closed the floating window (×) for this meeting.
@@ -112,6 +115,8 @@ class CicadaApp : Application() {
})
Log.d("app: launch ${if (BuildConfig.DEBUG) "dev" else "release"} sdk=${Build.VERSION.SDK_INT}")
if (ling.hasKey) background.execute { ling.check() }
+ updates = AppUpdates(this)
+ updates.start()
}
fun loadStrings() {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
index 835e556..f46e5fc 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -80,6 +80,14 @@ class DebugReceiver : BroadcastReceiver() {
"clip" -> app.getSystemService(android.content.ClipboardManager::class.java).setPrimaryClip(android.content.ClipData.newPlainText("test", arg))
"onboarded" -> { app.settings.onboarded = arg != "off"; app.saveSettings() }
"key" -> { app.key.reload(); app.ling.keyChanged(); app.background.execute { app.ling.check() } }
+ // 检查更新 against a test feed: the dev build checks only once one is set.
+ "updatefeed" -> { app.updates.setFeed(if (arg.isEmpty() || arg.contains("://")) arg else File(app.filesDir, arg).path); app.updates.checkIfDue(0) }
+ "update" -> when (arg) {
+ "check" -> app.updates.checkNow()
+ "download" -> app.updates.download()
+ "job" -> app.background.execute { app.updates.checkInBackground() }
+ "notify" -> app.updates.available?.let { app.updates.notifyAbout(it) }
+ }
"import" -> {
val s = Session.read(File(app.filesDir, arg).readText()) ?: return mapOf("error" to "unreadable")
app.store.import(s)
@@ -125,6 +133,9 @@ class DebugReceiver : BroadcastReceiver() {
"canOverlay" to app.canOverlay,
"sessions" to app.store.all().size,
"ui" to Strings.language,
+ "update" to mapOf("enabled" to app.updates.enabled, "current" to app.updates.checker.current, "available" to app.updates.available?.version,
+ "apk" to app.updates.available?.apk, "lastChecked" to app.updates.checker.lastChecked, "notified" to app.settings.updateNotified,
+ "manual" to app.updates.manual),
)
}
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
index d58f2aa..e5d0729 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
@@ -15,6 +15,8 @@ import cicada.Languages
import cicada.Session
import cicada.SessionStore
import cicada.Strings.L
+import cicada.Strings.LF
+import cicada.UpdateChecker
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
@@ -56,6 +58,7 @@ class MainActivity : Activity() {
unobserve = cicada.observe(::render)
shownTop = null; shownRecent = null
render()
+ cicada.updates.checkIfDue(UpdateChecker.STALE)
cicada.main.postDelayed(tick, 1000)
}
@@ -73,7 +76,7 @@ class MainActivity : Activity() {
val app = cicada
val file = app.importing
val key = listOf(NotesViews.liveKey(app), app.autoEnded, app.settings.source, app.settings.target, app.canOverlay, app.settings.overlay, micDenied, app.listen.spoken,
- app.startProblem, file?.done?.toInt()).joinToString("|")
+ app.startProblem, file?.done?.toInt(), app.updates.available?.version).joinToString("|")
if (key == shownTop) return
shownTop = key
top.removeAllViews()
@@ -84,6 +87,8 @@ class MainActivity : Activity() {
else -> startCard()
})
if (app.settings.overlay && !app.canOverlay && file == null) column.addView(tipCard())
+ // A new version, under the start card; never while a meeting or a file is going on.
+ app.updates.available?.takeIf { file == null && !app.listen.listening }?.let { column.addView(updateCard(it)) }
top.addView(column)
}
@@ -172,6 +177,23 @@ class MainActivity : Activity() {
addView(ui.textButton(L("去开启")) { OverlayGuideActivity.open(this@MainActivity, direct = true) })
}
+ /// 有新版本: 更新 downloads the APK in the browser, the words open the release notes.
+ private fun updateCard(u: UpdateChecker.Update) = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ background = ui.rounded(Palette.card, 22)
+ setPadding(ui.dp(16), ui.dp(12), ui.dp(8), ui.dp(12))
+ addView(ui.tile(R.drawable.i_update, 40, Palette.accentPale, Palette.link).apply { background = ui.rounded(Palette.accentPale, 20) })
+ // The words open the release notes (a bigger target than the grey line alone).
+ val texts = ui.stack(2, ui.text(LF("有新版本 %@", u.version), 15f, Palette.ink, medium = true), ui.helper(L("更新说明"))).apply {
+ setPadding(ui.dp(6), ui.dp(4), ui.dp(6), ui.dp(4))
+ contentDescription = LF("有新版本 %@", u.version) + "," + L("更新说明")
+ ui.tappable(this, 12) { cicada.updates.openNotes() }
+ }
+ addView(texts, ui.weight().apply { leftMargin = ui.dp(6) })
+ addView(ui.textButton(L("更新")) { cicada.updates.download() })
+ }
+
/// The meetings, newest first, under 今天 / 昨天 / the date (the last 60; search finds the rest).
private fun renderRecent() {
val app = cicada
@@ -234,7 +256,7 @@ class MainActivity : Activity() {
val meta = if (live) "${time(s.startedAt)} · ${Languages.clock(s.durationSeconds)}"
else listOfNotNull("${time(s.startedAt)}", Languages.clock(s.durationSeconds), "${s.lines.size} ${L("句")}", from).joinToString(" · ")
val todos = s.notes?.todos?.size ?: 0
- val trailing = if (todos > 0) ui.badge(cicada.Strings.LF("%@ 个待办", todos), Palette.body, Palette.ground) else null
+ val trailing = if (todos > 0) ui.badge(LF("%@ 个待办", todos), Palette.body, Palette.ground) else null
return ui.listRow(title, meta, trailing = trailing, titleView = titleView) {
activity.startActivity(Intent(activity, if (live) ListeningActivity::class.java else RecordActivity::class.java).putExtra("id", s.id))
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
index 005ae92..33b4970 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
@@ -46,7 +46,7 @@ class SettingsActivity : Activity() {
private fun build() {
val app = cicada
val s = app.settings
- val key = listOf(app.ling.keyState, app.key.read()?.takeLast(4), s.toJson(), app.canOverlay, Strings.language).joinToString("|")
+ val key = listOf(app.ling.keyState, app.key.read()?.takeLast(4), s.toJson(), app.canOverlay, Strings.language, app.updates.available?.version, app.updates.manual).joinToString("|")
if (key == shown) return
shown = key
page.removeAllViews()
@@ -110,11 +110,24 @@ class SettingsActivity : Activity() {
ui.listRow(L("导入录音或视频"), L("转成一场会议记录")) { startActivity(Intent(this, ImportActivity::class.java)) },
ui.listRow(L("重看新手引导")) { startActivity(Intent(this, OnboardingActivity::class.java)) }) +
// Android 13+ can add the tile from here; older versions edit Quick Settings by hand.
- if (android.os.Build.VERSION.SDK_INT >= 33) listOf(ui.listRow(L("添加到快捷设置"), L("下拉通知栏,一键开始或结束听")) { addTile() }) else emptyList()))
+ (if (android.os.Build.VERSION.SDK_INT >= 33) listOf(ui.listRow(L("添加到快捷设置"), L("下拉通知栏,一键开始或结束听")) { addTile() }) else emptyList()) +
+ listOf(updateRow())))
val version = packageManager.getPackageInfo(packageName, 0).versionName
page.addView(ui.helper("${L("知了")} $version · Android").apply { gravity = Gravity.CENTER; setPadding(0, ui.dp(20), 0, 0) })
}
+ /// 检查更新: its answer on the right; with a new version found, tapping it downloads that.
+ private fun updateRow(): View {
+ val u = cicada.updates
+ val found = u.available
+ val trailing = when {
+ found != null -> ui.text(Strings.LF("有新版本 %@", found.version), 15f, Palette.link, bold = true, lines = 1)
+ u.manual != null -> value(u.manual!!)
+ else -> null
+ }
+ return ui.listRow(L("检查更新"), trailing = trailing, chevron = false) { if (found != null) u.download() else u.checkNow() }
+ }
+
private fun addTile() {
if (android.os.Build.VERSION.SDK_INT < 33) return
getSystemService(android.app.StatusBarManager::class.java).requestAddTileService(
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt
new file mode 100644
index 0000000..5bfcf82
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt
@@ -0,0 +1,151 @@
+package com.wquguru.cicada
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.job.JobInfo
+import android.app.job.JobParameters
+import android.app.job.JobScheduler
+import android.app.job.JobService
+import android.content.ComponentName
+import android.content.Intent
+import android.net.Uri
+import cicada.Log
+import cicada.Strings.L
+import cicada.Strings.LF
+import cicada.UpdateChecker
+
+/// 检查更新 (the Windows App's Updates part): finds a newer APK on GitHub Releases and says so on
+/// 首页 (below the start card, not while listening), in 设置 › 其他, and once per version in a
+/// notification. 更新 hands the APK link to the browser; the system installer does the rest.
+class AppUpdates(private val app: CicadaApp) {
+ val checker = UpdateChecker(app.packageManager.getPackageInfo(app.packageName, 0).versionName ?: "0", app.settings.updateLastChecked)
+ /// Release builds check; the dev build only once `updatefeed` points it somewhere.
+ @Volatile var enabled = !BuildConfig.DEBUG; private set
+ /// 检查更新 in 设置: null, or the answer to the last manual check for a few seconds.
+ @Volatile var manual: String? = null; private set
+ private val clearManual = Runnable { manual = null; app.changed() }
+
+ val available get() = if (enabled) checker.available else null
+
+ fun start() {
+ checker.onChange {
+ app.main.post {
+ app.settings.updateLastChecked = checker.lastChecked
+ app.settings.save()
+ if (checker.available == null) cancelNotification()
+ app.changed()
+ }
+ }
+ // Updated since the last notification: it is about this version or an older one.
+ app.settings.updateNotified?.let { if (!UpdateChecker.isNewer(it, checker.current)) cancelNotification() }
+ if (!enabled) return
+ schedule()
+ checkIfDue(UpdateChecker.STALE)
+ }
+
+ fun checkIfDue(age: Long) { if (enabled) app.background.execute { checker.checkIfDue(age) } }
+
+ /// The debug command `updatefeed`: another release JSON, checked now.
+ fun setFeed(feed: String) {
+ checker.feed = feed.ifEmpty { UpdateChecker.FEED }
+ enabled = true
+ schedule()
+ Log.d("update: feed set")
+ }
+
+ /// 检查更新: says 正在检查… / 已是最新版本 / 连不上 GitHub for a few seconds.
+ fun checkNow() {
+ if (manual == L("正在检查…")) return
+ enabled = true
+ app.main.removeCallbacks(clearManual)
+ manual = L("正在检查…"); app.changed()
+ app.background.execute {
+ val reached = checker.check()
+ app.main.post {
+ manual = if (checker.available != null) null else if (reached) L("已是最新版本") else L("连不上 GitHub,请稍后再试")
+ app.changed()
+ app.main.postDelayed(clearManual, 4000)
+ }
+ }
+ }
+
+ /// 更新: the browser downloads the APK (or shows the release page when there is none).
+ fun download() { available?.let { open(it.apk ?: it.page); Log.d("update: download ${it.version}") } }
+
+ fun openNotes() { available?.let { open(it.page) } }
+
+ private fun open(url: String) {
+ try { app.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
+ catch (e: Exception) { Log.d("update: open failed ${e.javaClass.simpleName}") }
+ }
+
+ // MARK: In the background
+
+ /// About once a day while the phone has a network; the job survives a restart.
+ private fun schedule() {
+ try {
+ val js = app.getSystemService(JobScheduler::class.java)
+ if (js.getPendingJob(JOB) != null) return
+ val r = js.schedule(JobInfo.Builder(JOB, ComponentName(app, UpdateJob::class.java))
+ .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
+ .setPeriodic(24 * 3600_000L, 6 * 3600_000L)
+ .setPersisted(true)
+ .build())
+ Log.d("update: job scheduled ${r == JobScheduler.RESULT_SUCCESS}")
+ } catch (e: Exception) { Log.d("update: job not scheduled ${e.javaClass.simpleName}") }
+ }
+
+ /// The job's check: a new version gets one notification, unless Cicada is in front (首页 says
+ /// it) or a meeting is going on (the next run tells, the version not yet marked as told).
+ fun checkInBackground() {
+ if (!enabled) return
+ checker.check()
+ val u = checker.available ?: return
+ app.main.post {
+ if (app.settings.updateNotified == u.version) return@post
+ if (app.foreground || app.listen.listening) { Log.d("update: ${u.version} not notified now"); return@post }
+ notifyAbout(u)
+ }
+ }
+
+ fun notifyAbout(u: UpdateChecker.Update) {
+ val nm = app.getSystemService(NotificationManager::class.java)
+ nm.createNotificationChannel(NotificationChannel(CHANNEL, L("检查更新"), NotificationManager.IMPORTANCE_DEFAULT))
+ fun view(code: Int, url: String) = PendingIntent.getActivity(app, code, Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val n = Notification.Builder(app, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(LF("有新版本 %@", u.version))
+ .setContentText(L("点按更新"))
+ .setContentIntent(view(10, u.apk ?: u.page))
+ .addAction(Notification.Action.Builder(null, L("更新说明"), view(11, u.page)).build())
+ .setAutoCancel(true)
+ .build()
+ nm.notify(NOTIFICATION, n)
+ app.settings.updateNotified = u.version
+ app.settings.save()
+ Log.d("update: notified ${u.version}")
+ }
+
+ private fun cancelNotification() = app.getSystemService(NotificationManager::class.java).cancel(NOTIFICATION)
+
+ companion object {
+ const val JOB = 7
+ const val NOTIFICATION = 2
+ private const val CHANNEL = "updates"
+ }
+}
+
+class UpdateJob : JobService() {
+ override fun onStartJob(params: JobParameters): Boolean {
+ val app = cicada
+ app.background.execute {
+ app.updates.checkInBackground()
+ jobFinished(params, false)
+ }
+ return true
+ }
+
+ override fun onStopJob(params: JobParameters) = true
+}
diff --git a/android/app/src/main/res/drawable/i_update.xml b/android/app/src/main/res/drawable/i_update.xml
new file mode 100644
index 0000000..5a5da77
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_update.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20z"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M16 12l-4-4l-4 4"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12 16V8"/>
+</vector>
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index f7840f9..e8a7213 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -173,3 +173,5 @@
"按住说话,松开后用对方的语言读出来" = "Hold to speak; let go and it's read aloud in their language";
"用手机的声音读一句英语" = "Hear an English sentence in the phone's voice";
"转成一场会议记录" = "Turn it into a meeting record";
+"更新" = "Update";
+"点按更新" = "Tap to update";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index 7f91e31..4eddffd 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -173,3 +173,5 @@
"按住说话,松开后用对方的语言读出来" = "押しながら話し、離すと相手の言語で読み上げます";
"用手机的声音读一句英语" = "スマホの声で英語を一文読み上げます";
"转成一场会议记录" = "会議記録にします";
+"更新" = "アップデート";
+"点按更新" = "タップしてアップデート";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index 0143f27..785db3e 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -173,3 +173,5 @@
"按住说话,松开后用对方的语言读出来" = "누른 채 말하고, 떼면 상대의 언어로 읽어 줘요";
"用手机的声音读一句英语" = "휴대전화 목소리로 영어 한 문장 듣기";
"转成一场会议记录" = "회의 기록으로 만들어요";
+"更新" = "업데이트";
+"点按更新" = "탭하여 업데이트";
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index db41b0e..7a1b5f4 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -24,6 +24,8 @@ object Tests {
"readsAMacRecordAndWritesItBackByteForByte" to ::readsAMacRecord,
"keepsTheMacsImportAndRoomFields" to ::keepsTheMacsImportAndRoomFields,
"jsonEdgeCases" to ::jsonEdgeCases,
+ "findsTheNewestAndroidRelease" to ::findsTheNewestAndroidRelease,
+ "updateCheckIsSilentAndDue" to ::updateCheckIsSilentAndDue,
"renamesLikeTheMac" to ::renamesLikeTheMac,
"theLiveMeetingCantBeDeleted" to ::theLiveMeetingCantBeDeleted,
"followSystemLikeTheMac" to ::followSystemLikeTheMac,
@@ -821,4 +823,69 @@ object Tests {
equal(java.time.Instant.parse("2026-11-04T10:00:06Z"), store.get(s.id)?.endedAt, "endedAt")
equal("已经 10 分钟没人说话", Strings.LF("已经 %lld 分钟没人说话", 10), "number placeholder")
}
+
+ private fun release(tag: String, vararg assets: String, draft: Boolean = false, pre: Boolean = false) = mapOf(
+ "tag_name" to tag, "html_url" to "https://github.com/wquguru/cicada/releases/tag/$tag", "draft" to draft, "prerelease" to pre,
+ "assets" to assets.map { mapOf("name" to it, "browser_download_url" to "https://github.com/dl/$it", "size" to 1234L) })
+
+ fun findsTheNewestAndroidRelease() {
+ val feed = Json.write(listOf(
+ release("v1.10.0", "Cicada-1.10.0.dmg"), // Mac only: skipped
+ release("v1.11.0", "Cicada-1.11.0-Android.apk", draft = true),
+ release("v1.12.0", "Cicada-1.12.0-Android.apk", pre = true),
+ release("v1.9.2", "Cicada-1.9.2-Windows-x64.zip", "Cicada-1.9.2-Android.apk"),
+ release("v1.9.10", "Cicada-1.9.10-Android.apk"),
+ ), pretty = false)
+ val u = UpdateChecker.newestAndroid(UpdateChecker.decode(feed)!!)
+ equal("1.9.10", u?.version, "newest with an APK")
+ equal("https://github.com/dl/Cicada-1.9.10-Android.apk", u?.apk, "apk url")
+ equal(1234L, u?.size, "size")
+ equal("1.9.2", UpdateChecker.newestAndroid(UpdateChecker.decode(Json.write(release("v1.9.2", "Cicada-1.9.2-Android.apk")))!!)?.version, "one release")
+ equal(null, UpdateChecker.decode("{\"message\":\"Not Found\"}"), "an error object")
+ equal(null, UpdateChecker.decode("<html>"), "not JSON")
+ check(UpdateChecker.isNewer("2.10.0", "2.9.1"), "2.10 > 2.9")
+ check(!UpdateChecker.isNewer("1.4.0", "1.4.0-dev"), "suffix ignored")
+ check(!UpdateChecker.isNewer("1.4", "1.4.0"), "missing part is 0")
+ check(UpdateChecker.isNewer("1.4.1", "1.4"), "patch")
+ }
+
+ fun updateCheckIsSilentAndDue() {
+ val ok = object : Transport {
+ var calls = 0
+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {
+ calls++
+ check(headers["User-Agent"] != null, "User-Agent sent")
+ return Transport.Response(200, Json.write(listOf(release("v2.0.0", "Cicada-2.0.0-Android.apk"))))
+ }
+ }
+ val c = UpdateChecker("1.9.0", null, ok)
+ var told = 0
+ c.onChange { told++ }
+ check(c.check(), "reached")
+ equal("2.0.0", c.available?.version, "newer found")
+ equal(1, told, "listeners told")
+ check(c.lastChecked != null, "remembers when")
+ check(c.checkIfDue(UpdateChecker.STALE), "not due is fine")
+ equal(1, ok.calls, "not due: no request")
+ equal(null, UpdateChecker("2.0.0", null, ok).apply { check() }.available, "same version: nothing")
+ val down = UpdateChecker("1.9.0", null, object : Transport {
+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int) = Transport.Response(403, "{}")
+ })
+ check(!down.check(), "rate-limited is a failure")
+ equal(null, down.lastChecked, "and not remembered")
+ val day = 24 * 3600_000L
+ val now = 10 * day
+ check(UpdateChecker.due(null, now, day), "never checked")
+ check(!UpdateChecker.due(now - 1000, now, day), "just checked")
+ check(UpdateChecker.due(now - day, now, day), "old enough")
+ check(UpdateChecker.due(now + 1000, now, day), "clock set back")
+ val file = File(Paths.root, "feed.json").apply { writeText(Json.write(release("v3.0.0", "Cicada-3.0.0-Android.apk"))) }
+ equal("3.0.0", UpdateChecker("1.0.0").apply { feed = file.path; check() }.available?.version, "a file feed")
+ equal("3.0.0", UpdateChecker("1.0.0").apply { feed = file.toURI().toString(); check() }.available?.version, "a file:// feed")
+ val s = AppSettings(updateLastChecked = 1_762_000_000_123L, updateNotified = "2.0.0")
+ s.save()
+ val back = AppSettings.load()
+ equal(1_762_000_000_123L, back.updateLastChecked, "lastChecked kept")
+ equal("2.0.0", back.updateNotified, "notified kept")
+ }
}
diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.kt
index 26e3b20..a24f2f6 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -30,6 +30,10 @@ class AppSettings(
var recordAudio: Boolean = true,
/// 把我说的翻译给对方: 按住说话 in 面对面 (the Mac's 同声传译 switch).
var speakBack: Boolean = true,
+ /// When GitHub Releases last answered an update check (epoch ms; UpdateChecker).
+ var updateLastChecked: Long? = null,
+ /// The newest version a notification was posted for, so each one is announced once.
+ var updateNotified: String? = null,
) {
/// My language: the translate-to choice, or under "follow system" the Mac's myLanguage
/// (Chinese when the system list has it, else the first). 我说, notes and the UI start from it.
@@ -46,6 +50,7 @@ class AppSettings(
"showInCapture" to showInCapture, "onboarded" to onboarded, "uiLanguage" to uiLanguage,
"source" to source, "overlay" to overlay, "silenceEnd" to silenceEnd, "silenceMinutes" to silenceMinutes,
"speakerVoices" to speakerVoices, "recordAudio" to recordAudio, "speakBack" to speakBack,
+ "updateLastChecked" to updateLastChecked, "updateNotified" to updateNotified,
)
fun save() {
@@ -76,6 +81,7 @@ class AppSettings(
silenceMinutes = (o["silenceMinutes"] as? Number)?.toDouble() ?: d.silenceMinutes,
speakerVoices = o["speakerVoices"].bool() ?: true, recordAudio = o["recordAudio"].bool() ?: true,
speakBack = o["speakBack"].bool() ?: true,
+ updateLastChecked = (o["updateLastChecked"] as? Number)?.toLong(), updateNotified = o["updateNotified"].str(),
)
}
}
diff --git a/android/core/src/main/kotlin/cicada/Updates.kt b/android/core/src/main/kotlin/cicada/Updates.kt
new file mode 100644
index 0000000..e213a99
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/Updates.kt
@@ -0,0 +1,106 @@
+package cicada
+
+import java.io.File
+import java.net.URI
+
+/// Checks GitHub Releases for an Android build newer than the running one, as the Windows
+/// UpdateChecker: the app checks at launch, when 首页 comes back once the answer is an hour old,
+/// and from a daily job. Failures (offline, rate-limited, 404) are silent. This only finds the
+/// update: the browser downloads the APK and the system installer replaces the app (it refuses
+/// one signed with another key), so no install permission is needed.
+/// `check` blocks: run it off the main thread.
+class UpdateChecker(
+ /// The running version, three parts ("1.4.0"), from VERSION via versionName.
+ val current: String,
+ /// When the feed last answered (epoch ms), kept in settings across launches.
+ @Volatile var lastChecked: Long? = null,
+ private val transport: Transport = UrlTransport,
+) {
+ class Update(val version: String, val page: String, val apk: String?, val size: Long)
+
+ /// The list, not `releases/latest`: a release that ships only the Mac or Windows has no APK,
+ /// so the newest Android release may be further down. The `updatefeed` debug command points
+ /// it at another release JSON (a list or one release); a file path or file:// URL works too.
+ @Volatile var feed = FEED
+
+ /// The newer release, or null (none, or not checked yet).
+ @Volatile var available: Update? = null; private set
+ private val listeners = mutableListOf<() -> Unit>()
+
+ fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
+
+ fun checkIfDue(age: Long, now: Long = System.currentTimeMillis()): Boolean = if (due(lastChecked, now, age)) check() else true
+
+ /// False when the feed couldn't be reached or answered with something unexpected. One at a
+ /// time: a second caller (检查更新 during the launch check) waits, then asks for itself.
+ @Synchronized fun check(): Boolean {
+ try {
+ val releases = decode(read(feed)) ?: run { Log.d("update: feed unreadable"); return false }
+ val newest = newestAndroid(releases)
+ lastChecked = System.currentTimeMillis()
+ available = newest?.takeIf { isNewer(it.version, current) }
+ Log.d("update: checked, latest Android ${newest?.version ?: "none"}, running $current")
+ synchronized(listeners) { listeners.toList() }.forEach { it() }
+ return true
+ } catch (e: Exception) {
+ Log.d("update: check failed ${e.javaClass.simpleName}")
+ return false
+ }
+ }
+
+ private fun read(feed: String): String {
+ if (feed.startsWith("file:")) return File(URI(feed)).readText()
+ if (!feed.contains("://")) return File(feed).readText()
+ // GitHub's API refuses requests without a User-Agent.
+ val r = transport.send(feed, "GET", null, mapOf("User-Agent" to "Cicada-Android", "Accept" to "application/vnd.github+json"), 20_000)
+ if (r.status !in 200..299) throw java.io.IOException("HTTP ${r.status}")
+ return r.body
+ }
+
+ companion object {
+ const val FEED = "https://api.github.com/repos/wquguru/cicada/releases?per_page=20"
+ /// 首页 coming back checks once the last answer is this old; the daily job does the rest.
+ const val STALE = 3600_000L
+
+ fun due(last: Long?, now: Long, age: Long): Boolean =
+ // A clock set back leaves `last` in the future: check rather than wait for it.
+ last == null || now - last >= age || last > now
+
+ /// A list of releases, or one release (a feed pointed at `releases/latest`).
+ fun decode(text: String): List<Map<String, Any?>>? {
+ val v = try { Json.parse(text) } catch (_: Json.ParseException) { return null }
+ return when (v) {
+ is List<*> -> v.mapNotNull { it.obj() }
+ is Map<*, *> -> v.obj()?.takeIf { !it["tag_name"].str().isNullOrEmpty() }?.let { listOf(it) }
+ else -> null
+ }
+ }
+
+ /// The newest published release with an Android APK; one without only carries other platforms.
+ fun newestAndroid(releases: List<Map<String, Any?>>): Update? {
+ var best: Update? = null
+ for (r in releases) {
+ if (r["draft"].bool() == true || r["prerelease"].bool() == true) continue
+ val apk = r["assets"].arr().mapNotNull { it.obj() }.firstOrNull {
+ val name = it["name"].str() ?: ""
+ name.startsWith("Cicada-") && name.endsWith("-Android.apk")
+ } ?: continue
+ val u = Update((r["tag_name"].str() ?: continue).trimStart('v'), r["html_url"].str() ?: "",
+ apk["browser_download_url"].str(), apk["size"].num()?.toLong() ?: 0)
+ if (best == null || isNewer(u.version, best.version)) best = u
+ }
+ return best
+ }
+
+ /// Dotted numeric versions: "2.10.0" is newer than "2.9.1"; a suffix ("1.4.0-dev") is ignored.
+ fun isNewer(a: String, b: String): Boolean {
+ fun parts(v: String) = v.substringBefore('-').split('.').map { it.toIntOrNull() ?: 0 }
+ val x = parts(a); val y = parts(b)
+ for (i in 0 until maxOf(x.size, y.size)) {
+ val l = x.getOrElse(i) { 0 }; val r = y.getOrElse(i) { 0 }
+ if (l != r) return l > r
+ }
+ return false
+ }
+ }
+}
diff --git a/site/changelog.json b/site/changelog.json
index 4a1bcf0..fbad960 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -16,6 +16,11 @@
"title": "Linux 版有新版本时会提示,点一下就更新并重新打开。",
"text": "顶栏菜单第一项和设置 › 关于都会显示;下载后先核对校验值再安装,正在听时等会议结束再装。"
},
+ {
+ "kind": "new",
+ "title": "Android 版有新版本时会提示,点“更新”就下载新的安装包。",
+ "text": "首页开始卡下面和设置 › 其他 › 检查更新都会显示,每个新版本还会发一次通知;正在听时不提示。装上后设置和会议记录都保留。"
+ },
{
"kind": "fixed",
"title": "Linux 上打开知了总会出现会议记录窗口,没设置完时引导叠在上面。",