Feature: add file management to the Android client

Android 客户端此前没有文件管理:声明了 CLIENT_CAP_V2 却没有实现,主控的
文件管理对话框和 MCP 的 list_files/download_file/upload_file 对 APK 只会
超时。本次复用 Linux/macOS 已在用的 common/FileManager.h,只补平台差异:

- 盘符模型:P=应用私有目录、I=内部存储、S/T/...=SD 卡与 U 盘;V2 上传
  通过 FileTransferV2::SetPathMapper 复用同一套映射。
- 文件通道线上是 GBK。NDK 的 iconv 要 API 28,客户端 minSdk 是 21,改走
  JNI -> Java Charset(NativeText.kt),严格模式失败原样透传。
- Android 11+ 引导开启「所有文件访问」;未授权时只挂 P: 并回一条提示。
  API <=29 用运行时存储权限 + requestLegacyExternalStorage。
- 顺带实现 COMMAND_SEARCH_FILE(深度 32、1 万条),并让 MCP 的
  list_files/download_file/upload_file/read_file 对 APK 开闸。

验证:arm64/armeabi 与模拟器 ABI 编译通过;模拟器上用 MCP 完成列盘、
列目录、下载、上传、中文文件名往返,GUI 文件管理器正常显示 P:/I:/S:。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
yuanyuanxiangandClaude Code committed 2026-11-16 18:34:46 +01:00
1 parent 7172ab376d
commit 28c0c9a2a6
9 files changed
+1001 -19

No files matched your search

@@ -2,11 +2,16 @@ package com.yama.client
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
@@ -17,11 +22,17 @@ class MainActivity : AppCompatActivity() {
private lateinit var projectionManager: MediaProjectionManager
// 授权流程只能走一次:从「所有文件访问」系统设置返回时 onResume 会再来一遍
private var flowStarted = false
private var awaitingStorageSettings = false
companion object {
const val REQUEST_MEDIA_PROJECTION = 1001
// POST_NOTIFICATIONS(API 33+)与 RECORD_AUDIO(语音监听)合并成一次请求;
// 结果回来后再弹录屏授权,两个系统对话框不会叠在一起。
// POST_NOTIFICATIONS(API 33+)、RECORD_AUDIO(语音监听)与 API 29- 的存储权限
// 合并成一次请求;结果回来后再弹录屏授权,系统对话框不会叠在一起。
const val REQUEST_PERMISSIONS = 1002
private const val PREF_NAME = "yama"
private const val PREF_ASKED_ALL_FILES = "asked_all_files"
}
override fun onCreate(savedInstanceState: Bundle?) {
@@ -47,7 +58,66 @@ class MainActivity : AppCompatActivity() {
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
if (savedInstanceState != null) { finish(); return }
// Android 11+:文件管理要「所有文件访问」,第一次启动引导一次。
// 不开启不影响其它功能,文件管理只能看到应用自己的目录(客户端会回提示)。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
!Environment.isExternalStorageManager() && !hasAskedAllFiles()) {
AlertDialog.Builder(this)
.setTitle("文件管理权限")
.setMessage(
"为了让主控浏览和传输本机文件,需要开启「所有文件访问」。\n\n" +
"请到 设置 → 应用 → YAMA → 所有文件访问 中开启。\n\n" +
"不开启也能正常使用远程控制等其它功能,只是文件管理只能看到应用自己的目录。")
.setPositiveButton("去开启") { _, _ ->
markAskedAllFiles()
awaitingStorageSettings = true
val intent = Intent(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:$packageName"))
val opened = runCatching { startActivity(intent) }.isSuccess ||
runCatching {
startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
}.isSuccess
if (!opened) {
// 两个设置入口都打不开(极简 ROM):别把启动流程卡住
awaitingStorageSettings = false
continueStart()
}
}
.setNegativeButton("以后再说") { _, _ ->
markAskedAllFiles()
continueStart()
}
.setCancelable(false)
.show()
return
}
continueStart()
}
override fun onResume() {
super.onResume()
// 从「所有文件访问」设置页返回:继续未完成的启动流程
if (awaitingStorageSettings) {
awaitingStorageSettings = false
continueStart()
}
}
private fun continueStart() {
if (flowStarted) return
flowStarted = true
val missing = ArrayList<String>()
// Android 10 及以下走运行时存储权限(Android 10 另靠 requestLegacyExternalStorage)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
missing.add(Manifest.permission.READ_EXTERNAL_STORAGE)
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
missing.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
@@ -65,6 +135,15 @@ class MainActivity : AppCompatActivity() {
startProjection()
}
private fun hasAskedAllFiles(): Boolean =
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.getBoolean(PREF_ASKED_ALL_FILES, false)
private fun markAskedAllFiles() {
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit().putBoolean(PREF_ASKED_ALL_FILES, true).apply()
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
@@ -0,0 +1,57 @@
package com.yama.client
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction
/**
* 文件管理通道的 GBK ↔ UTF-8 转换。
*
* 线上协议(与服务端 FileManagerDlg / MCP 的文件通道一致)是 GBK/ANSI:服务端按
* CP936 下发路径、按 CP936 解析客户端上报的文件名。Android 的文件系统路径是
* UTF-8,所以两端都要转一次。
*
* 为什么不在 native 用 iconv:NDK 的 iconv 从 API 28 才提供,客户端 minSdk 是 21,
* 低版本设备上链接/加载会失败。
*
* 严格模式:GBK 转换失败(例如路径里含 GBK 表示不了的字符)时**原样返回输入**,
* 与 Linux/macOS 客户端的 iconvConvert 行为一致;服务端对这类路径本来就会直传
* UTF-8 字节(见 McpServer.cpp 里 list_files 的注释),两边才能对上。
*/
object NativeText {
private val GBK: Charset = Charset.forName("GBK")
@JvmStatic
fun gbkToUtf8(bytes: ByteArray): ByteArray {
if (bytes.isEmpty()) return bytes
return try {
val dec = GBK.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
text.toByteArray(Charsets.UTF_8)
} catch (e: Exception) {
bytes
}
}
@JvmStatic
fun utf8ToGbk(bytes: ByteArray): ByteArray {
if (bytes.isEmpty()) return bytes
return try {
val dec = Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
val enc = GBK.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
val buf = enc.encode(java.nio.CharBuffer.wrap(text))
val out = ByteArray(buf.remaining())
buf.get(out)
out
} catch (e: Exception) {
bytes
}
}
}
@@ -0,0 +1,97 @@
package com.yama.client
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.os.storage.StorageManager
import android.util.Log
import java.io.File
/**
* 文件管理(COMMAND_LIST_DRIVE)的存储根枚举。
*
* 服务端文件管理器按 Windows 的盘符模型显示远程目录,所以这里把 Android 的存储
* 挂成盘符:
* P: 应用私有目录(永远可读,未授予「所有文件访问」时是唯一可用的根)
* I: 内部存储(/storage/emulated/0)
* S:/T:/… SD 卡、U 盘等可移动存储
*
* 权限:Android 11+ 需要 MANAGE_EXTERNAL_STORAGE(设置 → 应用 → YAMA → 所有文件访问);
* 未授予时 A: 仍可用,I:/S: 是否出现取决于系统是否允许列目录(scoped storage 下
* 大多能列出名字但读不了别人的文件),因此主控侧可能看到操作失败——这是权限问题的
* 预期表现,native 侧会在打开文件管理器时发一条提示。
*/
object StorageHelper {
private const val TAG = "YAMA_FS"
@JvmStatic
fun roots(): Array<String> {
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return emptyArray()
val out = ArrayList<String>()
// 应用私有目录:filesDir 对自身永远可读,作为降级根。
// 用 P:(Private)而不是 A::服务端对话框把 A/B 固定按软驱图标显示。
runCatching {
val appDir = ctx.filesDir?.absolutePath
if (!appDir.isNullOrEmpty()) add(out, 'P', appDir, "App data", false)
}
@Suppress("DEPRECATION")
val internal = runCatching { Environment.getExternalStorageDirectory()?.absolutePath }
.getOrNull()
if (!internal.isNullOrEmpty() && canList(internal))
add(out, 'I', internal, "Internal storage", false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val sm = ctx.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
var letter = 'S'
runCatching { sm?.storageVolumes }.getOrNull()?.forEach { vol ->
if (vol.isPrimary) return@forEach
val dir = runCatching { vol.directory?.absolutePath }.getOrNull()
if (!dir.isNullOrEmpty() && canList(dir) && letter <= 'Z') {
add(out, letter, dir, "SD card", true)
letter++
}
}
} else {
// API 21-29 没有 StorageVolume.getDirectory(),直接扫 /storage
var letter = 'S'
runCatching { File("/storage").listFiles() }.getOrNull()
?.sortedBy { it.name }
?.forEach { f ->
val name = f.name
if (name == "emulated" || name == "self") return@forEach
if (f.isDirectory && canList(f.absolutePath) && letter <= 'Z') {
add(out, letter, f.absolutePath, "SD card", true)
letter++
}
}
}
Log.i(TAG, "roots=" + out.joinToString("; "))
return out.toTypedArray()
}
/** 是否具备整机文件访问能力(Android 11+ 的「所有文件访问」) */
@JvmStatic
fun allFilesAccess(): Boolean {
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return runCatching { Environment.isExternalStorageManager() }.getOrDefault(false)
}
return ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED
}
private fun add(out: MutableList<String>, letter: Char, path: String,
label: String, removable: Boolean) {
// 去尾斜杠;服务端拼路径时统一自己加分隔符
val clean = if (path.length > 1 && path.endsWith('/')) path.dropLast(1) else path
out.add("$letter|$clean|$label|${if (removable) 1 else 0}")
}
private fun canList(path: String): Boolean =
runCatching { File(path).list() != null }.getOrDefault(false)
}