V1.4.2: 修复极米 H1S(Android 5.1.1) 一打开就闪退 —— 存储根目录写死导致
真正根因(用崩溃诊断包在该机上逐步定位得出,非此前推测的 API 守卫问题): - AppPaths 把存储根写死成 /storage/emulated/0/MaidongKTV,该机上此路径不可写, ensureDirectories() 里 check(it.exists() || it.mkdirs()) 抛异常 → onCreate 中断 → App 一打开就闪退(该机历来所有版本均如此)。 - 定位过程: 逐条语句打启动轨迹 + 把异常直接写进轨迹通道,最终锁定 「oc431 之后、oc432 之前」= AppPaths.ensureDirectories();包上 try/catch 后 App 立即可正常打开,确认根因。 修复: - AppPaths 改为运行时解析可写根目录: Environment 外部根 → 历史硬编码路径 → getExternalFilesDir() → filesDir,取第一个「可建且可写」的(幂等 init)。 - AppPaths.init(context) 在 KtvApplication.attachBaseContext 最前面调用, 早于任何 AppPaths 访问;路径成员由 val 改为 getter。 - ensureDirectories() 不再抛异常,返回 Boolean;MainActivity 拿到 false 只告警继续。 - 去掉编译期内联的路径常量: MuseDatabase.VIDEO_ROOT(const→getter)、 defaultDbFile()/findDatabaseFile() 改用 AppPaths.databaseFile (否则改存储根后 DB 仍指向硬编码路径)。 - 用户可见的目录提示文案改用 AppPaths.*Dir.absolutePath。 - 启动上报一行 STORAGE root=.. by=.. envState=.. probe=[..] 到远程日志, 便于排查不同盒子的存储差异。 验证: - DEX 中「内联的完整 DB 路径」由 1 处 → 0 处。 - 单元测试 2/2 通过;lint NewApi 闸门通过;签名证书不变(可覆盖 1.4.0/诊断包)。 - AGENTS.md 增补「存储根目录必须运行时解析」条目。 说明: versionCode 18~21 被本机临时诊断包占用,本版取 22 以便直接覆盖安装。
This commit is contained in:
@@ -160,7 +160,7 @@ $BT/apksigner verify 目标名.apk
|
||||
|
||||
### 版本号
|
||||
|
||||
- `app/build.gradle`:`versionName "1.4.1"` / `versionCode 17`
|
||||
- `app/build.gradle`:`versionName "1.4.2"` / `versionCode 22`(18~21 被本机临时诊断包占用过)
|
||||
- App 内显示统一用纯版本号(不加 `(versionCode)` 括号)
|
||||
- ⚠️ **发布构建已开启 NewApi 闸门**(`lint { checkReleaseBuilds true; fatal += ['NewApi'] }`):
|
||||
任何「调用了高于 `minSdk 21` 且未做版本守卫的 API」都会让 `assembleRelease` 直接失败。
|
||||
@@ -188,6 +188,24 @@ $BT/apksigner verify 目标名.apk
|
||||
在 `app/build/reports/lint-results-release.txt` 里搜 `NewApi`。
|
||||
- 根因扫描捷径:`grep -n "private val .* = object : android\." app/src/main/java/com/local/ktv/*.kt`
|
||||
—— 字段初始化器里出现 `android.*` 的高版本类就是要闪退。
|
||||
- **⚠️ 存储根目录必须运行时解析(不要再写死 `/storage/emulated/0`)**:
|
||||
`AppPaths` 曾把根目录写死成 `/storage/emulated/0/MaidongKTV`,在**极米 H1S(GMUI2.0 / Android 5.1.1)**
|
||||
上该路径不可写 → `ensureDirectories()` 的 `check(it.exists() || it.mkdirs())` 抛异常 →
|
||||
**App 一打开就闪退**(这台机器历来所有版本都打不开的真正原因,2026-09-26 定位)。
|
||||
现在的约定:
|
||||
1. `AppPaths.init(context)` 在 `KtvApplication.attachBaseContext` **最前面**调用,按
|
||||
「`Environment.getExternalStorageDirectory()` → 历史硬编码路径 → `getExternalFilesDir()`
|
||||
→ `filesDir`」顺序挑**第一个真正可建且可写**的目录(幂等);
|
||||
2. 所有用到根路径的地方必须走 `AppPaths.*` 的 **getter**,**绝不能用 `const val` 把路径编译期内联**
|
||||
(`MuseDatabase.VIDEO_ROOT`、`MuseDatabase.defaultDbFile()` 曾经就是 `const val` 内联的,
|
||||
改存储根后必须一起改成运行时取值);
|
||||
3. 目录创建**不许抛异常**:`AppPaths.ensureDirectories()` 返回 `Boolean`,失败只记日志,
|
||||
`MainActivity` 拿到 false 也只是告警继续,绝不能让存储问题变成闪退;
|
||||
4. 用户可见的目录提示文案也要用 `AppPaths.*Dir.absolutePath` 拼,不要写死 `/sdcard/...`;
|
||||
5. 启动时会往远程日志打一行 `STORAGE root=... by=... envState=... probe=[...]`,
|
||||
换盒子/换 ROM 时先看这行就能确认存储根落在哪。
|
||||
- 自查:`grep -rn "/storage/emulated\|/sdcard/MaidongKTV" app/src/main/java --include='*.kt'`
|
||||
除 `AppPaths` 的候选清单外不应再有硬编码。
|
||||
- **歌曲源**:`app/src/main/assets/mobile/ktv_api.js` 的 `CONFIG.HOSTS`(多源自动排序,失败源沉底)
|
||||
- **JS 热更新**:改动 `ktv_api.js` 必须同步提升 `KTV_BRIDGE_API: N` 标记(JS 与 `KtvJsBridge.kt` 两处校验),否则设备仍用缓存旧脚本
|
||||
- **曲库**:只走官方 Muse 同步(`MuseDbSync`),不再依赖代码仓库数据库文件
|
||||
|
||||
+2
-2
@@ -11,8 +11,8 @@ android {
|
||||
applicationId "com.local.ktv"
|
||||
minSdk 21
|
||||
targetSdk 25
|
||||
versionCode 17
|
||||
versionName "1.4.1"
|
||||
versionCode 22
|
||||
versionName "1.4.2"
|
||||
ndk {
|
||||
// 双 ABI 打包:兼容 64 位(Exynos 1580 等 arm64-v8a)与 32 位设备(极米 Play 超越版
|
||||
// 的 Amlogic 950X2/S905X2 采用 32 位 Android 用户态,必须包含 armeabi-v7a,否则
|
||||
|
||||
@@ -1,35 +1,124 @@
|
||||
package com.local.ktv
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/** The only external-storage namespace used by the fresh Maidong KTV app. */
|
||||
/**
|
||||
* 麦动 KTV 的存储命名空间。
|
||||
*
|
||||
* ⚠️ **历史实现把根目录写死成 `/storage/emulated/0/MaidongKTV`**,在部分定制 TV 盒子
|
||||
* (极米 H1S / GMUI2.0 / Android 5.1.1 = API 22)上该路径不可写:`ensureDirectories()`
|
||||
* 里 `check(it.exists() || it.mkdirs())` 失败抛异常,**App 一打开就闪退**。
|
||||
*
|
||||
* 现在改为**运行时解析**:按「设备真实外部存储根 → 历史硬编码路径 → App 私有外部目录 →
|
||||
* 内部目录」顺序挑第一个真正**可创建且可写**的目录,保证目录一定建得出来,
|
||||
* 曲库/下载/状态不因存储差异而不可用。
|
||||
*
|
||||
* 调用约定:`Application.attachBaseContext` 里**最先**调用 [init],早于任何 AppPaths 访问。
|
||||
*/
|
||||
object AppPaths {
|
||||
private const val TAG = "AppPaths"
|
||||
|
||||
/** 历史路径(作为候选之一保留,并与老版本数据保持兼容)。 */
|
||||
const val ROOT_PATH = "/storage/emulated/0/MaidongKTV"
|
||||
const val VIDEO_PATH = "$ROOT_PATH/video"
|
||||
|
||||
val root = File(ROOT_PATH)
|
||||
val stateFile = File(root, "state.json")
|
||||
val songsDir = File(root, "songs")
|
||||
val importDir = File(root, "import")
|
||||
val catalogFile = File(root, "catalog.json")
|
||||
val recordsDir = File(root, "records")
|
||||
val moviesDir = File(root, "movies")
|
||||
val appsDir = File(root, "apps")
|
||||
val backupDir = File(root, "backup")
|
||||
val databaseDir = File(root, "database")
|
||||
val databaseFile = File(databaseDir, "muse.db")
|
||||
val videoDir = File(VIDEO_PATH)
|
||||
val cloudSongsDir = File(videoDir, "cloud-song")
|
||||
@Volatile private var baseDir: File = File(ROOT_PATH)
|
||||
|
||||
fun ensureDirectories() {
|
||||
listOf(root, songsDir, importDir, recordsDir, moviesDir, appsDir, backupDir,
|
||||
databaseDir, videoDir, cloudSongsDir).forEach {
|
||||
check(it.exists() || it.mkdirs()) { "Cannot create ${it.absolutePath}" }
|
||||
/** 命中的候选标识(诊断用)。 */
|
||||
@Volatile private var resolvedBy: String = "default(not-initialized)"
|
||||
|
||||
/** 全部候选的探测结果(诊断用)。 */
|
||||
@Volatile private var probeResult: String = ""
|
||||
|
||||
val root: File get() = baseDir
|
||||
val stateFile: File get() = File(root, "state.json")
|
||||
val songsDir: File get() = File(root, "songs")
|
||||
val importDir: File get() = File(root, "import")
|
||||
val catalogFile: File get() = File(root, "catalog.json")
|
||||
val recordsDir: File get() = File(root, "records")
|
||||
val moviesDir: File get() = File(root, "movies")
|
||||
val appsDir: File get() = File(root, "apps")
|
||||
val backupDir: File get() = File(root, "backup")
|
||||
val databaseDir: File get() = File(root, "database")
|
||||
val databaseFile: File get() = File(databaseDir, "muse.db")
|
||||
val videoDir: File get() = File(root, "video")
|
||||
val cloudSongsDir: File get() = File(videoDir, "cloud-song")
|
||||
|
||||
/** 实际使用的根目录与候选探测结果(单行,便于远程日志检索)。 */
|
||||
fun storageFacts(context: Context): String {
|
||||
val env = runCatching { Environment.getExternalStorageDirectory()?.absolutePath }.getOrNull()
|
||||
val envState = runCatching { Environment.getExternalStorageState() }.getOrNull()
|
||||
val extFiles = runCatching { context.getExternalFilesDir(null)?.absolutePath }.getOrNull()
|
||||
val files = runCatching { context.filesDir?.absolutePath }.getOrNull()
|
||||
return buildString {
|
||||
append("root=").append(baseDir.absolutePath)
|
||||
append(" by=").append(resolvedBy)
|
||||
append(" writable=").append(runCatching { baseDir.canWrite() }.getOrDefault(false))
|
||||
append(" env=").append(env)
|
||||
append(" envState=").append(envState)
|
||||
append(" extFiles=").append(extFiles)
|
||||
append(" files=").append(files)
|
||||
append(" probe=[").append(probeResult).append(']')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析出一个**真正可写**的根目录。可重复调用(幂等)。
|
||||
* 放在 `Application.attachBaseContext` 最前面,保证后续任何 AppPaths 访问都拿到正确值。
|
||||
*/
|
||||
fun init(context: Context) {
|
||||
if (resolvedBy != "default(not-initialized)") return
|
||||
val app = runCatching { context.applicationContext }.getOrDefault(context)
|
||||
|
||||
val candidates = LinkedHashMap<String, File>()
|
||||
runCatching { Environment.getExternalStorageDirectory() }.getOrNull()?.let {
|
||||
candidates["env(${it.absolutePath})"] = File(it, "MaidongKTV")
|
||||
}
|
||||
candidates["legacy($ROOT_PATH)"] = File(ROOT_PATH)
|
||||
runCatching { app.getExternalFilesDir(null) ?: app.filesDir }.getOrNull()?.let {
|
||||
candidates["private(${it.absolutePath})"] = File(it, "MaidongKTV")
|
||||
}
|
||||
runCatching { app.filesDir }.getOrNull()?.let {
|
||||
candidates["internal(${it.absolutePath})"] = File(it, "MaidongKTV")
|
||||
}
|
||||
|
||||
val envState = runCatching { Environment.getExternalStorageState() }.getOrNull() ?: "?"
|
||||
val report = StringBuilder()
|
||||
candidates.forEach { (tag, dir) ->
|
||||
val ok = runCatching { (dir.isDirectory || dir.mkdirs()) && dir.canWrite() }
|
||||
.getOrDefault(false)
|
||||
if (report.isNotEmpty()) report.append("; ")
|
||||
report.append(tag).append('=').append(if (ok) "ok" else "fail")
|
||||
if (ok && resolvedBy == "default(not-initialized)") {
|
||||
baseDir = dir
|
||||
resolvedBy = tag
|
||||
}
|
||||
}
|
||||
probeResult = report.toString()
|
||||
Log.i(TAG, "storage root = ${baseDir.absolutePath} by=$resolvedBy envState=$envState")
|
||||
Log.i(TAG, "storage probe = $probeResult")
|
||||
}
|
||||
|
||||
/** 建目录。**永不抛异常**:存储不可用时只返回 false 并记录,由上层给出明确提示,而不是闪退。 */
|
||||
fun ensureDirectories(): Boolean {
|
||||
var allOk = true
|
||||
listOf(root, songsDir, importDir, recordsDir, moviesDir, appsDir, backupDir,
|
||||
databaseDir, videoDir, cloudSongsDir).forEach { dir ->
|
||||
val ok = runCatching { dir.exists() || dir.mkdirs() }.getOrDefault(false)
|
||||
if (!ok) {
|
||||
allOk = false
|
||||
Log.w(TAG, "cannot create directory: ${dir.absolutePath}")
|
||||
}
|
||||
}
|
||||
return allOk
|
||||
}
|
||||
|
||||
/** The original IJK binary creates this log folder internally; remove it after native startup. */
|
||||
fun removeNativeLegacyLogDirectory() {
|
||||
File("/storage/emulated/0/muse").deleteRecursively()
|
||||
val env = runCatching { Environment.getExternalStorageDirectory()?.absolutePath }.getOrNull()
|
||||
?: "/storage/emulated/0"
|
||||
runCatching { File("$env/muse").deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
package com.local.ktv
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.liulishuo.okdownload.OkDownload
|
||||
|
||||
class KtvApplication : Application() {
|
||||
/**
|
||||
* 存储根目录必须在**任何** AppPaths 访问之前解析好:
|
||||
* 部分定制盒子(极米 H1S / Android 5.1.1)上 `/storage/emulated/0` 不可写,
|
||||
* 历史实现直接崩溃。这里用 attachBaseContext 抢在所有业务代码之前完成探测。
|
||||
*/
|
||||
override fun attachBaseContext(base: Context?) {
|
||||
super.attachBaseContext(base)
|
||||
base?.let {
|
||||
runCatching { AppPaths.init(it) }
|
||||
.onFailure { error -> Log.e(TAG, "AppPaths.init failed", error) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instanceRef = this
|
||||
|
||||
@@ -425,7 +425,11 @@ class MainActivity : AppCompatActivity() {
|
||||
requestStorage()
|
||||
return
|
||||
}
|
||||
AppPaths.ensureDirectories()
|
||||
// 存储目录建不出来时**不再闪退**(极米 H1S / Android 5.1.1 的历史崩溃点),
|
||||
// AppPaths.init 已在 Application.attachBaseContext 里挑好可写根目录。
|
||||
if (!AppPaths.ensureDirectories()) {
|
||||
Log.w(TAG, "存储目录创建失败: ${AppPaths.storageFacts(this)}")
|
||||
}
|
||||
store.load()
|
||||
loadStateFromStore()
|
||||
stateDatabase = KtvStateDatabase(applicationContext)
|
||||
@@ -466,6 +470,8 @@ class MainActivity : AppCompatActivity() {
|
||||
playbackEngine = KtvPlaybackEngine(applicationContext)
|
||||
// 远程日志系统(GlogCenter): 启动即上报设备/网络信息。
|
||||
MiliLog.init(applicationContext)
|
||||
// 存储根目录探测结果(排查不同盒子存储差异用;单行便于按 STORAGE 检索)。
|
||||
MiliLog.info("STORAGE ${AppPaths.storageFacts(this)}")
|
||||
refreshLogDeviceContext()
|
||||
reportDeviceBootInfo()
|
||||
// 歌曲源窗口/风控到期守卫: 源对陌生出口 IP 可能在短暂窗口后返回 403,
|
||||
@@ -1705,7 +1711,7 @@ class MainActivity : AppCompatActivity() {
|
||||
panel.addView(sectionTitle("本地导入"))
|
||||
panel.addView(
|
||||
label(
|
||||
"请把歌曲放入 /sdcard/MaidongKTV/import、/sdcard/MaidongKTV/songs、U盘/KTV 或 U盘/songs,支持 mp4/mkv/avi/mp3/flac/wav。",
|
||||
"请把歌曲放入 ${AppPaths.importDir.absolutePath}、${AppPaths.songsDir.absolutePath}、U盘/KTV 或 U盘/songs,支持 mp4/mkv/avi/mp3/flac/wav。",
|
||||
20,
|
||||
Color.LTGRAY
|
||||
)
|
||||
@@ -2995,7 +3001,7 @@ class MainActivity : AppCompatActivity() {
|
||||
val adapter = tvAdapter()
|
||||
val apks = localApks()
|
||||
for (apk in apks) adapter.add(apk.getName() + " " + formatSize(apk.length()))
|
||||
if (adapter.isEmpty()) adapter.add("暂无 APK,请放入 /sdcard/MaidongKTV/apps 或 U盘/apps")
|
||||
if (adapter.isEmpty()) adapter.add("暂无 APK,请放入 ${AppPaths.appsDir.absolutePath} 或 U盘/apps")
|
||||
list.setAdapter(adapter)
|
||||
list.setOnItemClickListener(OnItemClickListener { p: AdapterView<*>?, v: View?, pos: Int, id: Long ->
|
||||
if (pos >= 0 && pos < apks.size) installApk(apks.get(pos))
|
||||
@@ -4196,7 +4202,7 @@ class MainActivity : AppCompatActivity() {
|
||||
content!!.addView(left, LinearLayout.LayoutParams(dp(300), -1))
|
||||
left.addView(sectionTitle("影片操作"))
|
||||
left.addView(button("扫描影片目录", View.OnClickListener { v: View? -> showLocalMovies() }))
|
||||
left.addView(label("目录:/sdcard/MaidongKTV/movies 或 U盘/movies", 18, Color.LTGRAY))
|
||||
left.addView(label("目录:${AppPaths.moviesDir.absolutePath} 或 U盘/movies", 18, Color.LTGRAY))
|
||||
|
||||
val right = panel()
|
||||
content!!.addView(right, LinearLayout.LayoutParams(0, -1, 1f))
|
||||
|
||||
@@ -584,11 +584,14 @@ class MuseDatabase @JvmOverloads constructor(initialSourceFile: File? = null) {
|
||||
companion object {
|
||||
private const val TAG = "MuseDatabase"
|
||||
private const val DEFAULT_CDN_PATH = "https://pub.mcdn.cherryonline.cn/"
|
||||
private const val DEFAULT_DB_PATH = "${AppPaths.ROOT_PATH}/database/muse.db"
|
||||
const val PAGE_SIZE = 10
|
||||
/** 搜索结果条数统计上限:达到该值即视为“足够多”,终止 COUNT 扫描以加速检索。 */
|
||||
const val SEARCH_COUNT_CAP = 2000
|
||||
const val VIDEO_ROOT = AppPaths.VIDEO_PATH
|
||||
/**
|
||||
* 视频根目录。**必须是运行时取值**:存储根由 [AppPaths.init] 在启动时解析,
|
||||
* 不能再像以前那样用 `const val` 把 `/storage/emulated/0/...` 编译期内联进去。
|
||||
*/
|
||||
val VIDEO_ROOT: String get() = AppPaths.videoDir.absolutePath
|
||||
const val CLOUD_SONG_DIR = "cloud-song"
|
||||
const val LOCAL_SONG_DIR = "local"
|
||||
|
||||
@@ -623,10 +626,10 @@ class MuseDatabase @JvmOverloads constructor(initialSourceFile: File? = null) {
|
||||
fun songDirectories(): List<File> = listOf(AppPaths.cloudSongsDir)
|
||||
|
||||
@JvmStatic
|
||||
fun defaultDbFile(): File = File(DEFAULT_DB_PATH)
|
||||
fun defaultDbFile(): File = AppPaths.databaseFile
|
||||
|
||||
private fun findDatabaseFile(): File? {
|
||||
return File(DEFAULT_DB_PATH).takeIf { it.exists() && it.canRead() }
|
||||
return AppPaths.databaseFile.takeIf { it.exists() && it.canRead() }
|
||||
}
|
||||
|
||||
private fun pageArgs(limit: Int, offset: Int) = arrayOf(limit.toString(), offset.toString())
|
||||
|
||||
Reference in New Issue
Block a user