feat: 新增列表页与新 Activity 跳转,修复切页后点击失效

- 服务端:新增列表页(8 条数据 + 页内滚动),点击目标与 actionId 均由文档下发
- Android:新增 RemoteDocumentActivity,actionId=2 时在新 Activity 中打开指定页面
- 修复:文档缓存改为缓存原始字节、每次渲染重新解析;复用同一个 CoreDocument 时
  旧点击回调会残留在 idActionListeners 中,导致守卫跳过注册,切页后点击完全失效
- 部署:k8s 镜像更新为 composeremote/server:1.0.0-list
This commit is contained in:
tongtong committed 2026-11-24 18:36:27 +08:00
1 parent 8a5d0375a6
commit 0b27edcbea
6 files changed
+193 -34

No files matched your search

@@ -25,6 +25,11 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity
android:name=".RemoteDocumentActivity"
android:exported="false"
android:label="@string/app_name"
android:theme="@style/Theme.ComposeRemoteAndroid" />
</application> </application>
</manifest> </manifest>
@@ -1,5 +1,6 @@
package com.ttstd.composeremote package com.ttstd.composeremote
import android.content.Intent
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
@@ -19,7 +20,15 @@ class MainActivity : ComponentActivity() {
ComposeRemoteAndroidTheme { ComposeRemoteAndroidTheme {
// 页面切换完全由服务端文档中的点击动作驱动,客户端只提供初始页面。 // 页面切换完全由服务端文档中的点击动作驱动,客户端只提供初始页面。
Box(modifier = Modifier.fillMaxSize().systemBarsPadding()) { Box(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
RemoteUIScreen() RemoteUIScreen(
// actionId = 2 的点击由服务端指定页面 id,这里用新 Activity 承载。
onOpenActivity = { page ->
startActivity(
Intent(this@MainActivity, RemoteDocumentActivity::class.java)
.putExtra(RemoteDocumentActivity.EXTRA_PAGE, page)
)
}
)
} }
} }
} }
@@ -0,0 +1,48 @@
package com.ttstd.composeremote
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import com.ttstd.composeremote.ui.RemoteUIScreen
import com.ttstd.composeremote.ui.theme.ComposeRemoteAndroidTheme
/**
* 在独立 Activity 中展示服务端下发的页面。
*
* 页面 id 由文档里的点击动作(actionId = 2)通过 Intent 传入;
* 已解析的文档在同一进程内缓存,因此再次打开不会重复下载和解析。
*/
class RemoteDocumentActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
val page = intent.getStringExtra(EXTRA_PAGE) ?: "detail"
setContent {
ComposeRemoteAndroidTheme {
Box(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
RemoteUIScreen(
startPage = page,
onOpenActivity = ::openRemotePage
)
}
}
}
}
private fun openRemotePage(page: String) {
startActivity(
Intent(this, RemoteDocumentActivity::class.java).putExtra(EXTRA_PAGE, page)
)
}
companion object {
const val EXTRA_PAGE = "com.ttstd.composeremote.extra.PAGE"
}
}
@@ -43,30 +43,35 @@ import java.util.concurrent.TimeUnit
*/ */
private const val ACTION_NAVIGATE = 1 private const val ACTION_NAVIGATE = 1
/** 与后端约定的 action id:把 metadata 当作页面 id,交给一个新的 Activity 打开。 */
private const val ACTION_OPEN_ACTIVITY = 2
private val client = OkHttpClient.Builder() private val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS)
.build() .build()
/** /**
* 已解析文档缓存。 * 文档原始字节缓存。
* *
* 切页时优先复用已解析的 [RemoteDocument],避免重复下载与重复解析; * 只缓存下载结果,不缓存 [RemoteDocument]:播放器的 [RemoteDocument] / CoreDocument
* 文档较大时解析成本高,因此只缓存有限个页面(LRU)。 * 是有状态的(画笔、点击区域、变量、点击回调都挂在同一个 CoreDocument 上),
* 同一个实例被重复 setDocument 到新的播放器时,旧的点击回调会残留在它自己的
* listener 集合里,导致新页面的点击失效。因此每次渲染都重新解析一份新的文档。
*/ */
private object RemoteDocumentStore { private object RemoteDocumentStore {
private const val MAX_ENTRIES = 8 private const val MAX_ENTRIES = 8
private val documents = object : private val documents = object :
LinkedHashMap<String, RemoteDocument>(MAX_ENTRIES, 0.75f, true) { LinkedHashMap<String, ByteArray>(MAX_ENTRIES, 0.75f, true) {
override fun removeEldestEntry( override fun removeEldestEntry(
eldest: MutableMap.MutableEntry<String, RemoteDocument>, eldest: MutableMap.MutableEntry<String, ByteArray>,
): Boolean = size > MAX_ENTRIES ): Boolean = size > MAX_ENTRIES
} }
fun get(page: String): RemoteDocument? = documents[page] fun get(page: String): ByteArray? = documents[page]
fun put(page: String, document: RemoteDocument) { fun put(page: String, bytes: ByteArray) {
documents[page] = document documents[page] = bytes
} }
} }
@@ -88,16 +93,15 @@ private suspend fun fetchRemoteUi(page: String, baseUrl: String): ByteArray =
} }
/** /**
* 下载并解析页面文档。 * 取出页面文档字节:命中缓存就不重复下载。
* *
* 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程。 * 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程。
*/ */
private suspend fun loadDocument(page: String, baseUrl: String): RemoteDocument { private suspend fun loadDocument(page: String, baseUrl: String): RemoteDocument {
RemoteDocumentStore.get(page)?.let { return it } val bytes = RemoteDocumentStore.get(page) ?: fetchRemoteUi(page, baseUrl).also {
val bytes = fetchRemoteUi(page, baseUrl) RemoteDocumentStore.put(page, it)
val document = withContext(Dispatchers.Default) { RemoteDocument(bytes) } }
RemoteDocumentStore.put(page, document) return withContext(Dispatchers.Default) { RemoteDocument(bytes) }
return document
} }
/** /**
@@ -114,6 +118,9 @@ private suspend fun loadDocument(page: String, baseUrl: String): RemoteDocument
*/ */
private class AntiAliasRemoteComposePlayer(context: Context) : RemoteComposePlayer(context) { private class AntiAliasRemoteComposePlayer(context: Context) : RemoteComposePlayer(context) {
/** 该播放器唯一的点击回调,文档切换后复用它。 */
var idActionCallback: RemoteComposePlayer.IdActionCallbacks? = null
/** /**
* `mInner` 是父类的 protected 字段,`mARContext` / `mPaintContext` / * `mInner` 是父类的 protected 字段,`mARContext` / `mPaintContext` /
* `mCachedPaintChanges` 是播放库内部字段,只能通过反射拿到; * `mCachedPaintChanges` 是播放库内部字段,只能通过反射拿到;
@@ -183,13 +190,27 @@ private fun Any.findDeclaredField(name: String): java.lang.reflect.Field? {
private fun RemoteDocumentView( private fun RemoteDocumentView(
document: RemoteDocument?, document: RemoteDocument?,
onNavigate: (String) -> Unit, onNavigate: (String) -> Unit,
onOpenActivity: ((String) -> Unit)?,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
// factory 只执行一次,用 rememberUpdatedState 保证回调始终指向最新的 lambda。 // factory 只执行一次,用 rememberUpdatedState 保证回调始终指向最新的 lambda。
val currentOnNavigate by rememberUpdatedState(onNavigate) val currentOnNavigate by rememberUpdatedState(onNavigate)
val currentOnOpenActivity by rememberUpdatedState(onOpenActivity)
AndroidView( AndroidView(
factory = { context -> AntiAliasRemoteComposePlayer(context) }, factory = { context ->
val player = AntiAliasRemoteComposePlayer(context)
// 每个播放器实例一个稳定的回调对象,避免同一个 view 反复注册。
player.idActionCallback = RemoteComposePlayer.IdActionCallbacks { actionId, metadata ->
if (!metadata.isNullOrBlank()) {
when (actionId) {
ACTION_NAVIGATE -> currentOnNavigate(metadata)
ACTION_OPEN_ACTIVITY -> currentOnOpenActivity?.invoke(metadata)
}
}
}
player
},
update = { view -> update = { view ->
if (document != null && view.tag !== document) { if (document != null && view.tag !== document) {
try { try {
@@ -198,14 +219,10 @@ private fun RemoteDocumentView(
// 文字绘制会重置画笔,因此在设置文档后再次确保抗锯齿生效。 // 文字绘制会重置画笔,因此在设置文档后再次确保抗锯齿生效。
view.enableAntiAliasing() view.enableAntiAliasing()
// 播放器只在已设置文档时才会真正登记点击回调,因此必须在 setDocument 之后注册。 // 播放器只在已设置文档时才会真正登记点击回调,因此必须在 setDocument 之后注册。
if (document.document.idActionListeners.isEmpty()) { // 文档每次都是新解析的(listener 集合为空),这里保证回调一定登记成功。
view.addIdActionListener( val callback = view.idActionCallback
RemoteComposePlayer.IdActionCallbacks { actionId, metadata -> if (callback != null && document.document.idActionListeners.isEmpty()) {
if (actionId == ACTION_NAVIGATE && !metadata.isNullOrBlank()) { view.addIdActionListener(callback)
currentOnNavigate(metadata)
}
}
)
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e("RemoteUIScreen", "文档加载失败", e) Log.e("RemoteUIScreen", "文档加载失败", e)
@@ -220,18 +237,17 @@ private fun RemoteDocumentView(
fun RemoteUIScreen( fun RemoteUIScreen(
startPage: String = "home", startPage: String = "home",
baseUrl: String = RemoteConfig.SERVER_BASE_URL, baseUrl: String = RemoteConfig.SERVER_BASE_URL,
onOpenActivity: ((String) -> Unit)? = null,
) { ) {
var page by rememberSaveable { mutableStateOf(startPage) } var page by rememberSaveable { mutableStateOf(startPage) }
var state by remember { mutableStateOf<RemoteUiState>(RemoteUiState.Loading) } var state by remember { mutableStateOf<RemoteUiState>(RemoteUiState.Loading) }
var retryToken by remember { mutableIntStateOf(0) } var retryToken by remember { mutableIntStateOf(0) }
LaunchedEffect(page, retryToken) { LaunchedEffect(page, retryToken) {
// 命中缓存时直接渲染,不闪 loading、不重复请求。 // 命中字节缓存时不闪 loading,也不会重复请求。
RemoteDocumentStore.get(page)?.let { if (RemoteDocumentStore.get(page) == null) {
state = RemoteUiState.Success(it) state = RemoteUiState.Loading
return@LaunchedEffect
} }
state = RemoteUiState.Loading
state = try { state = try {
RemoteUiState.Success(loadDocument(page, baseUrl)) RemoteUiState.Success(loadDocument(page, baseUrl))
} catch (e: Exception) { } catch (e: Exception) {
@@ -244,6 +260,7 @@ fun RemoteUIScreen(
RemoteDocumentView( RemoteDocumentView(
document = (state as? RemoteUiState.Success)?.document, document = (state as? RemoteUiState.Success)?.document,
onNavigate = { target -> page = target }, onNavigate = { target -> page = target },
onOpenActivity = onOpenActivity,
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) )
when (val current = state) { when (val current = state) {
+1 -1
View File
@@ -22,7 +22,7 @@ spec:
spec: spec:
containers: containers:
- name: server - name: server
image: composeremote/server:1.0.0-nav image: composeremote/server:1.0.0-list
imagePullPolicy: Never imagePullPolicy: Never
ports: ports:
- name: http - name: http
@@ -18,6 +18,7 @@ import androidx.compose.remote.creation.dsl.fillMaxWidth
import androidx.compose.remote.creation.dsl.height import androidx.compose.remote.creation.dsl.height
import androidx.compose.remote.creation.dsl.onClick import androidx.compose.remote.creation.dsl.onClick
import androidx.compose.remote.creation.dsl.padding import androidx.compose.remote.creation.dsl.padding
import androidx.compose.remote.creation.dsl.verticalScroll
import androidx.compose.remote.creation.profile.Profile import androidx.compose.remote.creation.profile.Profile
import androidx.compose.remote.creation.profile.RemoteComposeWriterFactory import androidx.compose.remote.creation.profile.RemoteComposeWriterFactory
@@ -33,6 +34,12 @@ private const val CANVAS_HEIGHT_DP = 900
/** 服务端与播放端约定的 action id:跳转到 metadata 里指定的页面。 */ /** 服务端与播放端约定的 action id:跳转到 metadata 里指定的页面。 */
private const val ACTION_NAVIGATE = 1 private const val ACTION_NAVIGATE = 1
/** 服务端与播放端约定的 action id:在新 Activity 中打开 metadata 指定的页面。 */
private const val ACTION_OPEN_ACTIVITY = 2
/** 列表页的数据条数(当前为演示数据,真实场景可替换为业务查询结果)。 */
private const val LIST_ITEM_COUNT = 8
fun buildRemoteDocument(page: String): ByteArray { fun buildRemoteDocument(page: String): ByteArray {
lateinit var profile: Profile lateinit var profile: Profile
profile = Profile( profile = Profile(
@@ -56,19 +63,21 @@ fun buildRemoteDocument(page: String): ByteArray {
// 跳转目标以文本形式随文档下发,播放端只负责把 metadata 当作页面 id 使用。 // 跳转目标以文本形式随文档下发,播放端只负责把 metadata 当作页面 id 使用。
val homeTarget = remoteText("home") val homeTarget = remoteText("home")
val detailTarget = remoteText("detail") val detailTarget = remoteText("detail")
val listTarget = remoteText("list")
Column( Column(
Modifier.fillMaxSize().background(WINDOW_BG).padding(RcDp(16f)) Modifier.fillMaxSize().background(WINDOW_BG).padding(RcDp(16f))
) { ) {
when (page) { when (page) {
"detail" -> detailContent(homeTarget) "detail" -> detailContent(homeTarget)
else -> homeContent(detailTarget) "list" -> listContent(homeTarget)
else -> homeContent(detailTarget, listTarget)
} }
} }
} }
} }
private fun RcScope.homeContent(detailTarget: RcText) { private fun RcScope.homeContent(detailTarget: RcText, listTarget: RcText) {
Text( Text(
text = "Remote Compose", text = "Remote Compose",
fontSize = RcSp(28f), fontSize = RcSp(28f),
@@ -94,6 +103,21 @@ private fun RcScope.homeContent(detailTarget: RcText) {
hint = "点击查看详情 →", hint = "点击查看详情 →",
target = detailTarget target = detailTarget
) )
Spacer(Modifier.height(RcDp(12f)))
card(
title = "列表",
body = "列表页由后端下发 8 条数据,可上下滚动查看。",
hint = "点击查看列表 →",
target = listTarget
)
Spacer(Modifier.height(RcDp(12f)))
card(
title = "新 Activity",
body = "这张卡片会在一个新的 Activity 中打开详情页。",
hint = "打开新 Activity →",
target = detailTarget,
actionId = ACTION_OPEN_ACTIVITY
)
} }
private fun RcScope.detailContent(homeTarget: RcText) { private fun RcScope.detailContent(homeTarget: RcText) {
@@ -124,13 +148,69 @@ private fun RcScope.detailContent(homeTarget: RcText) {
) )
} }
private fun RcScope.card(title: String, body: String, hint: String, target: RcText) { /**
* 列表页:内容全部由服务端生成,条目较多时可在页内上下滚动。
*/
private fun RcScope.listContent(homeTarget: RcText) {
Column(Modifier.fillMaxSize().verticalScroll()) {
Text(
text = "列表",
fontSize = RcSp(28f),
color = TITLE_COLOR
)
Spacer(Modifier.height(RcDp(4f)))
Text(
text = "服务端下发的 ${LIST_ITEM_COUNT} 条数据",
fontSize = RcSp(14f),
color = BODY_COLOR
)
Spacer(Modifier.height(RcDp(16f)))
repeat(LIST_ITEM_COUNT) { index ->
listItem(index + 1)
Spacer(Modifier.height(RcDp(8f)))
}
Spacer(Modifier.height(RcDp(4f)))
card(
title = "返回",
body = "回到首页。",
hint = "点击返回首页 →",
target = homeTarget
)
}
}
private fun RcScope.listItem(index: Int) {
Box(
Modifier
.fillMaxWidth()
.background(CARD_BG)
.padding(RcDp(12f))
) {
Column(Modifier.fillMaxWidth()) {
Text(text = "条目 $index", fontSize = RcSp(16f), color = TITLE_COLOR)
Spacer(Modifier.height(RcDp(4f)))
Text(
text = "这里是第 $index 条由后端下发的列表数据。",
fontSize = RcSp(13f),
color = BODY_COLOR
)
}
}
}
private fun RcScope.card(
title: String,
body: String,
hint: String,
target: RcText,
actionId: Int = ACTION_NAVIGATE,
) {
Box( Box(
Modifier Modifier
.fillMaxWidth() .fillMaxWidth()
.background(CARD_BG) .background(CARD_BG)
.padding(RcDp(16f)) .padding(RcDp(16f))
.onClick { hostAction(ACTION_NAVIGATE, target) } .onClick { hostAction(actionId, target) }
) { ) {
Column(Modifier.fillMaxWidth()) { Column(Modifier.fillMaxWidth()) {
Text(text = title, fontSize = RcSp(18f), color = TITLE_COLOR) Text(text = title, fontSize = RcSp(18f), color = TITLE_COLOR)