合并直传接收与文件选择优化

This commit is contained in:
zhy
2026-08-11 10:21:45 +08:00
7 changed files with 360 additions and 15 deletions
+3 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 16
versionName = "0.4.0-rc8"
versionCode = 17
versionName = "0.4.0-rc9"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -40,6 +40,7 @@ android {
dependencies {
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.core:core-ktx:1.15.0")
implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2")
+9
View File
@@ -19,6 +19,15 @@
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/qft_file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
@@ -79,6 +79,8 @@ class MainActivity : ComponentActivity() {
private var connectedNetwork: Network? = null
private var connectedBaseUrl: String? = null
private val selectedFiles = mutableListOf<SelectedFile>()
private var managingFilesForPair: PairingPayload? = null
private var managingFilesForBaseUrl: String? = null
private var sendStatusText: TextView? = null
private var sendFilesText: TextView? = null
private var sendProgress: ProgressBar? = null
@@ -115,13 +117,18 @@ class MainActivity : ComponentActivity() {
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear()
var unknown = 0
for (uri in uris) {
val file = UploadClient.describeFile(contentResolver, uri)
if (file != null) selectedFiles += file else unknown++
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
}
renderSelectedFiles()
val pair = managingFilesForPair
val baseUrl = managingFilesForBaseUrl
if (pair != null && baseUrl != null) {
showFileSelection(pair, baseUrl)
return@registerForActivityResult
}
if (unknown > 0) {
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
} else if (selectedFiles.isNotEmpty()) {
@@ -150,6 +157,8 @@ class MainActivity : ComponentActivity() {
downloadRunning = false
downloadStatusText = null
selectedFiles.clear()
managingFilesForPair = null
managingFilesForBaseUrl = null
val root = pageColumn()
root.addView(text("QFT", 30f, Color.WHITE, true))
@@ -175,6 +184,13 @@ class MainActivity : ComponentActivity() {
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
buttonLabel = "扫描电脑二维码",
) { requestScanner(ScannerMode.PAIR) })
root.addView(space(16))
root.addView(modeCard(
title = "接收文件柜",
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
body = "查看 QFT 已接收的文件;点击后将使用手机中可用的阅读器或播放器打开。",
buttonLabel = "打开文件柜",
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
@@ -723,22 +739,25 @@ class MainActivity : ComponentActivity() {
root.addView(space(14))
root.addView(card().apply {
addView(text("选择文件", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, MUTED)
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
setOnClickListener { showFileSelection(pair, baseUrl) }
}, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(card().apply {
addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
sendStatusText = text("请先选择需要传输的文件,再点击“开始传输”", 14f, WARNING)
addView(sendStatusText, matchWrap(top = 8))
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
sendButton = button("开始传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener { startUploads(pair, baseUrl) }
sendButton = button("选择传输文件").apply {
isEnabled = connectedBaseUrl != null
setOnClickListener {
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
else startUploads(pair, baseUrl)
}
}
addView(sendButton, matchWrap(top = 14))
})
@@ -819,10 +838,118 @@ class MainActivity : ComponentActivity() {
}
}
private fun showReceivedFiles(message: String? = null) {
val root = pageColumn()
root.addView(text("接收文件柜", 28f, Color.WHITE, true))
root.addView(text("QFT 已保存到 Downloads/QFT 的文件", 14f, MUTED))
message?.let { root.addView(text(it, 13f, WARNING), matchWrap(top = 10)) }
root.addView(space(16))
val files = try {
ReceivedFileCabinet.list(this)
} catch (e: Exception) {
emptyList()
}
if (files.isEmpty()) {
root.addView(card().apply {
addView(text("文件柜为空", 17f, Color.WHITE, true))
addView(text("完成电脑下发或光学接收后,文件会自动出现在这里。", 14f, MUTED), matchWrap(top = 8))
})
} else {
root.addView(text("共 ${files.size} 个文件", 13f, ACCENT, true))
files.forEach { file ->
val entry = card()
entry.addView(text(file.name, 16f, Color.WHITE, true))
entry.addView(
text("${humanBytes(file.size)} · ${file.mimeType.ifBlank { "未知格式" }}", 12f, MUTED),
matchWrap(top = 5),
)
entry.addView(button("打开文件").apply {
setOnClickListener {
try {
ReceivedFileCabinet.open(this@MainActivity, file)
} catch (e: Exception) {
showReceivedFiles("无法打开 ${file.name}:请安装支持该格式的阅读器。")
}
}
}, matchWrap(top = 10))
root.addView(entry, matchWrap(bottom = 10))
}
}
root.addView(space(12))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun showFileSelection(pair: PairingPayload, baseUrl: String) {
managingFilesForPair = pair
managingFilesForBaseUrl = baseUrl
val root = pageColumn()
root.addView(text("选择发送文件", 28f, Color.WHITE, true))
root.addView(text("可多次添加文件,并在列表中单独移除。", 14f, MUTED))
root.addView(space(14))
val total = selectedFiles.sumOf { it.size }
root.addView(card().apply {
addView(text("已选 ${selectedFiles.size} 个 · ${humanBytes(total)}", 16f, ACCENT, true))
if (selectedFiles.isEmpty()) {
addView(text("请先选择需要传输的文件", 14f, WARNING), matchWrap(top = 8))
} else {
selectedFiles.toList().forEach { file ->
val row = LinearLayout(this@MainActivity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
row.addView(
text("${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
)
row.addView(button("移除").apply {
setOnClickListener {
selectedFiles.removeAll { it.uri == file.uri }
showFileSelection(pair, baseUrl)
}
}, LinearLayout.LayoutParams(dp(82), dp(44)))
addView(row, matchWrap(top = 10))
}
}
})
root.addView(space(14))
root.addView(button("添加文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
})
if (selectedFiles.isNotEmpty()) {
root.addView(space(10))
root.addView(button("清空选择").apply {
setOnClickListener {
selectedFiles.clear()
showFileSelection(pair, baseUrl)
}
})
}
root.addView(space(10))
root.addView(button("完成并返回传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener {
managingFilesForPair = null
managingFilesForBaseUrl = null
showSendReady(pair, baseUrl)
}
})
root.addView(space(10))
root.addView(button("取消并返回传输").apply {
setOnClickListener {
managingFilesForPair = null
managingFilesForBaseUrl = null
showSendReady(pair, baseUrl)
}
})
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun renderSelectedFiles() {
val total = selectedFiles.sumOf { it.size }
sendFilesText?.text = if (selectedFiles.isEmpty()) {
"尚未选择文件"
"请先选择需要传输的文件"
} else {
buildString {
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
@@ -830,11 +957,17 @@ class MainActivity : ComponentActivity() {
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
}.trim()
}
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
sendButton?.isEnabled = connectedBaseUrl != null
}
private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return
if (selectedFiles.isEmpty()) {
sendStatusText?.setTextColor(WARNING)
sendStatusText?.text = "请先选择需要传输的文件"
showFileSelection(pair, baseUrl)
return
}
val files = selectedFiles.toList()
sendButton?.isEnabled = false
transferExecutor.execute {
@@ -0,0 +1,102 @@
package com.qft.optical
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import java.io.File
data class ReceivedFile(
val uri: Uri,
val name: String,
val size: Long,
val mimeType: String,
val modifiedAtSeconds: Long,
)
/** Lists only the files QFT has finished writing to Downloads/QFT. */
object ReceivedFileCabinet {
private const val RELATIVE_QFT_PATH = "Download/QFT/"
fun list(context: Context): List<ReceivedFile> =
if (Build.VERSION.SDK_INT >= 29) listModern(context.contentResolver) else listLegacy(context)
fun open(context: Context, file: ReceivedFile) {
val resolvedMime = mimeFor(file.name, file.mimeType)
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(file.uri, resolvedMime)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, "打开 ${file.name}"))
}
private fun listModern(resolver: ContentResolver): List<ReceivedFile> {
val projection = arrayOf(
MediaStore.Downloads._ID,
MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.SIZE,
MediaStore.Downloads.MIME_TYPE,
MediaStore.Downloads.DATE_MODIFIED,
)
val out = mutableListOf<ReceivedFile>()
resolver.query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
"${MediaStore.Downloads.RELATIVE_PATH}=? AND ${MediaStore.Downloads.IS_PENDING}=0",
arrayOf(RELATIVE_QFT_PATH),
"${MediaStore.Downloads.DATE_MODIFIED} DESC",
)?.use { cursor ->
val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID)
val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE)
val mimeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE)
val timeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DATE_MODIFIED)
while (cursor.moveToNext()) {
val id = cursor.getLong(idIndex)
val name = cursor.getString(nameIndex).orEmpty().ifBlank { "未命名文件" }
out += ReceivedFile(
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id),
name = name,
size = cursor.getLong(sizeIndex).coerceAtLeast(0L),
mimeType = cursor.getString(mimeIndex).orEmpty(),
modifiedAtSeconds = cursor.getLong(timeIndex),
)
}
}
return out
}
@Suppress("DEPRECATION")
private fun listLegacy(context: Context): List<ReceivedFile> {
val directory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"QFT",
)
return directory.listFiles()
?.asSequence()
?.filter { it.isFile }
?.sortedByDescending { it.lastModified() }
?.map { file ->
ReceivedFile(
uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file),
name = file.name,
size = file.length().coerceAtLeast(0L),
mimeType = mimeFor(file.name, ""),
modifiedAtSeconds = file.lastModified() / 1000L,
)
}
?.toList()
.orEmpty()
}
private fun mimeFor(name: String, supplied: String): String {
if (supplied.isNotBlank() && supplied != "application/octet-stream") return supplied
val extension = name.substringAfterLast('.', "").lowercase()
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
}
}
@@ -5,6 +5,7 @@ import android.database.Cursor
import android.net.Network
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Log
import org.json.JSONObject
import java.io.FileInputStream
import java.net.DatagramPacket
@@ -28,12 +29,16 @@ data class SelectedFile(
)
object UploadClient {
private const val TAG = "QftUpload"
private const val DISCOVERY_PORT = 39392
private const val CHUNK_SMALL = 4L * 1024L * 1024L
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
private const val CHUNK_LARGE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val STREAM_BUFFER = 1024 * 1024
// A single request is materially more reliable for small files on Wi-Fi
// Direct, and a 4 MiB parallel chunk gives no throughput benefit there.
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
// QFT Direct can briefly reset a TCP flow while the Android network route
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
// the Windows receiver treats a repeated chunk as an idempotent success.
@@ -222,7 +227,7 @@ object UploadClient {
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
if (pairing.version >= 2 && isSeekable(resolver, file)) {
if (pairing.version >= 2 && file.size >= PARALLEL_MIN_FILE_SIZE && isSeekable(resolver, file)) {
try {
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
return
@@ -236,6 +241,7 @@ object UploadClient {
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
}
}
Log.i(TAG, "using single-stream upload: size=${file.size}, endpoint=$baseUrl")
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
}
@@ -248,6 +254,11 @@ object UploadClient {
return block()
} catch (e: Throwable) {
last = e
Log.w(
TAG,
"$label: attempt=${attempt + 1}/$LOCAL_REQUEST_ATTEMPTS, ${failureSummary(e)}",
e,
)
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
Thread.currentThread().interrupt()
@@ -256,7 +267,23 @@ object UploadClient {
}
}
}
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last)
val failure = last ?: IllegalStateException("unknown local request failure")
throw IllegalStateException(
"$label,已重试 $LOCAL_REQUEST_ATTEMPTS 次:${failureSummary(failure)}",
failure,
)
}
private fun failureSummary(error: Throwable): String {
val chain = ArrayList<String>(3)
var current: Throwable? = error
while (current != null && chain.size < 3) {
val type = current.javaClass.simpleName.ifBlank { current.javaClass.name }
val detail = current.message?.replace(Regex("\\s+"), " ")?.take(240)
chain += if (detail.isNullOrBlank()) type else "$type: $detail"
current = current.cause
}
return chain.joinToString(" <- ")
}
private fun uploadParallel(
@@ -268,7 +295,9 @@ object UploadClient {
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
Log.i(TAG, "parallel init: size=${file.size}, endpoint=$baseUrl")
val init = initUpload(network, baseUrl, pairing, deviceName, file)
Log.i(TAG, "parallel init complete: chunks=${init.totalChunks}, chunkSize=${init.chunkSize}")
if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(0, 0)
@@ -362,6 +391,7 @@ object UploadClient {
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer,
) = retryLocalRequest("分块 $index 上传失败") {
Log.d(TAG, "chunk start: index=$index, bytes=$length, endpoint=$baseUrl")
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try {
conn.requestMethod = "POST"
@@ -391,6 +421,7 @@ object UploadClient {
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
try { conn.inputStream.close() } catch (_: Exception) {}
Log.d(TAG, "chunk complete: index=$index, bytes=$length")
} finally {
conn.disconnect()
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="qft_downloads" path="Download/QFT/" />
</paths>