74 lines
2.9 KiB
Kotlin
74 lines
2.9 KiB
Kotlin
package top.yeij.hearth.webview
|
||
|
||
import android.util.Log
|
||
import top.yeij.hearth.app.AppRepository
|
||
import top.yeij.hearth.card.Card
|
||
import top.yeij.hearth.card.CardRepository
|
||
import top.yeij.hearth.media.MediaSessionSource
|
||
import top.yeij.hearth.webapp.WebApp
|
||
import top.yeij.hearth.webapp.WebAppRepository
|
||
|
||
class JsBridge(
|
||
private val deviceWidthPx: Int,
|
||
private val deviceHeightPx: Int,
|
||
private val density: Float,
|
||
private val darkMode: Boolean,
|
||
private val appRepository: AppRepository? = null,
|
||
private val webAppRepository: WebAppRepository? = null,
|
||
private val cardRepository: CardRepository? = null,
|
||
) {
|
||
private val gson = com.google.gson.Gson()
|
||
|
||
@android.webkit.JavascriptInterface
|
||
fun getDeviceInfo(): String {
|
||
Log.d("HearthBridge", "getDeviceInfo called")
|
||
return gson.toJson(
|
||
mapOf(
|
||
"widthPx" to deviceWidthPx,
|
||
"heightPx" to deviceHeightPx,
|
||
"density" to density,
|
||
"darkMode" to darkMode
|
||
)
|
||
)
|
||
}
|
||
|
||
// 返回已安装应用列表 JSON(无仓库时返回空数组)
|
||
// Return installed app list JSON (empty array when no repository wired)
|
||
@android.webkit.JavascriptInterface
|
||
fun listApps(): String = appRepository?.listApps() ?: "[]"
|
||
|
||
// 启动指定包名应用,成功返回 true(无仓库时返回 false)
|
||
// Launch an app by package name, true on success (false when no repository wired)
|
||
@android.webkit.JavascriptInterface
|
||
fun launchApp(packageName: String): Boolean = appRepository?.launchApp(packageName) ?: false
|
||
|
||
// 返回 H5 应用清单 JSON(无仓库时返回空数组)
|
||
// Return the H5 web app manifest JSON (empty array when no repository wired)
|
||
@android.webkit.JavascriptInterface
|
||
fun fetchWebApps(): String = gson.toJson(webAppRepository?.fetchManifest() ?: emptyList<WebApp>())
|
||
|
||
// 返回首页卡片目录 JSON(无仓库时返回空数组;有仓库时由 fetchCatalog 保证内置 time 卡)
|
||
// Return the home card catalog JSON (empty array when no repository wired;
|
||
// fetchCatalog guarantees the builtin time card when wired)
|
||
@android.webkit.JavascriptInterface
|
||
fun fetchCards(): String {
|
||
val cards = cardRepository?.fetchCatalog() ?: emptyList<Card>()
|
||
Log.d("HearthBridge", "fetchCards: ${cards.size} cards")
|
||
return gson.toJson(cards)
|
||
}
|
||
|
||
// 注册媒体会话监听,回调推送给 H5(info 为 null 时推 "null")
|
||
// Register media session listener; push callbacks to H5 (push "null" when info is null)
|
||
fun setMediaListener(source: MediaSessionSource, webView: android.webkit.WebView) {
|
||
source.start { info ->
|
||
webView.post {
|
||
val json = info?.toJson() ?: "null"
|
||
webView.evaluateJavascript(
|
||
"window.HearthEvents && window.HearthEvents.mediaSessionChanged($json);",
|
||
null
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|