fix: add legacy-compatible Android phone link

This commit is contained in:
zhy200308
2026-08-12 16:40:43 +08:00
parent 2ff0741fff
commit ccaaab7002
12 changed files with 243 additions and 49 deletions
+3 -1
View File
@@ -16,7 +16,7 @@ v0.4.16 提供两套互不依赖的传输方式:
> v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。 > v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
## v0.5.0-dev3:Android → Android 手机互传 ## v0.5.0-dev4:Android → Android 手机互传
当前开发版新增 Android 手机之间的扫码直传闭环: 当前开发版新增 Android 手机之间的扫码直传闭环:
@@ -29,6 +29,8 @@ v0.4.16 提供两套互不依赖的传输方式:
- 发送二维码按当前应用窗口的实际可用宽高动态生成并居中,手机、平板和分屏窗口都不会再被 `match_parent` 放大溢出。 - 发送二维码按当前应用窗口的实际可用宽高动态生成并居中,手机、平板和分屏窗口都不会再被 `match_parent` 放大溢出。
- Android 7–9 接收端每次扫码都会用二维码中的新密码刷新临时 Wi-Fi 配置,不再复用同名热点的旧密码;Android 10+ 也只复用完整凭据一致的系统配网请求。 - Android 7–9 接收端每次扫码都会用二维码中的新密码刷新临时 Wi-Fi 配置,不再复用同名热点的旧密码;Android 10+ 也只复用完整凭据一致的系统配网请求。
- 当高版本发送机只能创建旧设备不支持的纯 WPA3 热点时,接收端会跳过无效的系统搜索,并自动尝试二维码内经过认证的原局域网地址。 - 当高版本发送机只能创建旧设备不支持的纯 WPA3 热点时,接收端会跳过无效的系统搜索,并自动尝试二维码内经过认证的原局域网地址。
- 手机发送端改为优先建立 Wi‑Fi Direct 兼容接入点:Android 10+ 强制 2.4 GHz,统一使用 WPA2,一张专用网同时供新旧 Android 自动配对;不支持时才回落 LocalOnlyHotspot/同局域网。
- 手机互传使用顺序 Range 接收以规避部分 Android 7–9 文件提供器并发读取损坏,并在生成二维码前校验文件选择器报告的大小与实际内容一致。
此阶段只实现 Android → Android;Android ↔ iOS 尚未接入。 此阶段只实现 Android → Android;Android ↔ iOS 尚未接入。
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical" applicationId = "com.qft.optical"
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 35
versionCode = 26 versionCode = 27
versionName = "0.5.0-dev3" versionName = "0.5.0-dev4"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
+1
View File
@@ -13,6 +13,7 @@
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" /> <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
<uses-feature android:name="android.hardware.camera.any" android:required="true" /> <uses-feature android:name="android.hardware.camera.any" android:required="true" />
<uses-feature android:name="android.hardware.wifi" android:required="false" /> <uses-feature android:name="android.hardware.wifi" android:required="false" />
<uses-feature android:name="android.hardware.wifi.direct" android:required="false" />
<application <application
android:allowBackup="false" android:allowBackup="false"
@@ -181,7 +181,7 @@ object DownloadClient {
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual") Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
discardTransferState(partial) discardTransferState(partial)
if (round + 1 >= VERIFY_ROUNDS) { if (round + 1 >= VERIFY_ROUNDS) {
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码") error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让发送端重新创建传输")
} }
onPhase("校验未通过,正在重新完整下载…") onPhase("校验未通过,正在重新完整下载…")
} }
@@ -550,7 +550,12 @@ object DownloadClient {
onProgress(initial, expectedSize) onProgress(initial, expectedSize)
if (ledger.allComplete()) return if (ledger.allComplete()) return
val workers = ledger.totalChunks.coerceAtMost(RANGE_WORKERS).coerceAtLeast(1) // Some Android 7–9 DocumentsProvider implementations expose a stream
// that is individually seekable but corrupts data when the same URI is
// opened concurrently. Phone → phone therefore downloads its ranges in
// deterministic order on one worker. PC senders keep the 8-way path.
val workerLimit = if (pairing.downloadPath.startsWith("/qft/phone/download/")) 1 else RANGE_WORKERS
val workers = ledger.totalChunks.coerceAtMost(workerLimit).coerceAtLeast(1)
Log.i(TAG, "parallel start: chunks=${ledger.totalChunks}, workers=$workers, completed=$initial/$expectedSize") Log.i(TAG, "parallel start: chunks=${ledger.totalChunks}, workers=$workers, completed=$initial/$expectedSize")
val pool = Executors.newFixedThreadPool(workers) val pool = Executors.newFixedThreadPool(workers)
val next = AtomicInteger(0) val next = AtomicInteger(0)
@@ -672,7 +677,7 @@ object DownloadClient {
val code = conn.responseCode val code = conn.responseCode
if (code != HttpURLConnection.HTTP_PARTIAL) { if (code != HttpURLConnection.HTTP_PARTIAL) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null } val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
error("发送端下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}") error("发送端下载服务未返回 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
} }
val expectedRange = "bytes $offset-$end/$expectedSize" val expectedRange = "bytes $offset-$end/$expectedSize"
if (conn.getHeaderField("Content-Range") != expectedRange) { if (conn.getHeaderField("Content-Range") != expectedRange) {
@@ -228,7 +228,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() }) ) { showReceivedFiles() })
root.addView(space(22)) root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED)) root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.5.0-dev3 · Android 7+ 到最新", 12f, MUTED)) root.addView(text("QFT v0.5.0-dev4 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
} }
@@ -925,10 +925,6 @@ class MainActivity : ComponentActivity() {
} }
private fun ensurePhoneHotspotPermissionThenStart() { private fun ensurePhoneHotspotPermissionThenStart() {
if (Build.VERSION.SDK_INT < 26) {
startPhoneShare()
return
}
val required = if (Build.VERSION.SDK_INT >= 33) { val required = if (Build.VERSION.SDK_INT >= 33) {
arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES) arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES)
} else { } else {
@@ -1041,7 +1037,10 @@ class MainActivity : ComponentActivity() {
) )
root.addView(phoneShareStatusText) root.addView(phoneShareStatusText)
root.addView(text( root.addView(text(
if (wifi != null) "临时网络:${wifi.ssid}\n发送服务端口:${server.port}" if (wifi != null) {
val link = if (wifi.ssid.startsWith("DIRECT-")) "兼容专用网络(2.4GHz / WPA2)" else "备用临时网络"
"$link:${wifi.ssid}\n发送服务端口:${server.port}"
}
else "连接方式:两台手机当前同一 Wi-Fi\n发送服务端口:${server.port}", else "连接方式:两台手机当前同一 Wi-Fi\n发送服务端口:${server.port}",
12f, MUTED, 12f, MUTED,
), matchWrap(top = 8)) ), matchWrap(top = 8))
@@ -2,15 +2,32 @@ package com.qft.optical
import android.content.Context import android.content.Context
import android.net.wifi.WifiManager import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pConfig
import android.net.wifi.p2p.WifiP2pManager
import android.os.Build import android.os.Build
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.os.SystemClock
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import java.security.SecureRandom
import java.util.concurrent.atomic.AtomicBoolean
/** Owns an Android LocalOnlyHotspot reservation for one phone-share session. */ /**
* Owns the phone-share access point.
*
* A second LocalOnlyHotspot request cannot create a second SSID: Android shares
* one underlying hotspot. QFT therefore prefers a Wi-Fi Direct group-owner AP,
* which is WPA2 and accepts legacy Wi-Fi stations. Android 10+ senders force it
* onto 2.4 GHz so Android 7-era receivers can see the same single network.
* LocalOnlyHotspot remains a fallback for OEMs that disable P2P group creation.
*/
class PhoneHotspotController(context: Context) { class PhoneHotspotController(context: Context) {
private val wifiManager = context.applicationContext.getSystemService(WifiManager::class.java) private val appContext = context.applicationContext
private val wifiManager = appContext.getSystemService(WifiManager::class.java)
private val p2pManager = appContext.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager
private val handler = Handler(Looper.getMainLooper())
private var reservation: AutoCloseable? = null private var reservation: AutoCloseable? = null
private var p2pChannel: WifiP2pManager.Channel? = null
private var generation = 0 private var generation = 0
fun start( fun start(
@@ -19,16 +36,136 @@ class PhoneHotspotController(context: Context) {
) { ) {
close() close()
val run = ++generation val run = ++generation
if (Build.VERSION.SDK_INT < 26) { startCompatibilityGroup(
onFailed("Android 7 不支持应用内临时热点,将使用当前局域网") run = run,
onStarted = onStarted,
onFallback = { reason ->
if (run != generation) return@startCompatibilityGroup
if (Build.VERSION.SDK_INT >= 26) {
startLocalOnlyHotspot(run, onStarted) { localReason ->
onFailed("$reason;$localReason")
}
} else {
onFailed("$reason;Android 7 无法创建备用临时热点,将使用当前局域网")
}
},
)
}
@Suppress("MissingPermission")
private fun startCompatibilityGroup(
run: Int,
onStarted: (WifiCredentials) -> Unit,
onFallback: (String) -> Unit,
) {
val manager = p2pManager ?: run {
onFallback("设备没有 Wi-Fi Direct 服务")
return return
} }
startApi26(run, onStarted, onFailed) val terminal = AtomicBoolean(false)
var localChannel: WifiP2pManager.Channel? = null
fun fallback(reason: String) {
if (run != generation || !terminal.compareAndSet(false, true)) return
val channel = localChannel
if (p2pChannel === channel) p2pChannel = null
if (channel != null) {
try {
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
override fun onSuccess() = onFallback(reason)
override fun onFailure(removeReason: Int) = onFallback(reason)
})
} catch (_: Exception) {
onFallback(reason)
}
} else {
onFallback(reason)
}
}
val channel = try {
manager.initialize(appContext, Looper.getMainLooper()) {
fallback("Wi-Fi Direct 通道已断开")
}
} catch (e: Exception) {
onFallback("初始化兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
return
}
localChannel = channel
p2pChannel = channel
val createListener = object : WifiP2pManager.ActionListener {
override fun onSuccess() {
val deadline = SystemClock.elapsedRealtime() + 12_000L
fun pollGroup() {
if (run != generation || terminal.get()) return
try {
manager.requestGroupInfo(channel) { group ->
if (run != generation || terminal.get()) return@requestGroupInfo
val ssid = group?.networkName.orEmpty()
val passphrase = group?.passphrase.orEmpty()
if (group?.isGroupOwner == true && ssid.isNotBlank() && passphrase.length in 8..63) {
if (!terminal.compareAndSet(false, true)) return@requestGroupInfo
onStarted(WifiCredentials(ssid, passphrase, "WPA2"))
} else if (SystemClock.elapsedRealtime() >= deadline) {
fallback("创建 2.4GHz/WPA2 兼容专用网络超时")
} else {
handler.postDelayed({ pollGroup() }, 180L)
}
}
} catch (e: Exception) {
fallback("读取兼容专用网络信息失败:${e.message ?: e.javaClass.simpleName}")
}
}
pollGroup()
}
override fun onFailure(reason: Int) {
fallback("系统拒绝创建 2.4GHz/WPA2 兼容专用网络(错误 $reason)")
}
}
fun createGroup() {
if (run != generation || terminal.get()) return
try {
if (Build.VERSION.SDK_INT >= 29) {
manager.createGroup(channel, compatibilityConfig(), createListener)
} else {
// API 24–28 creates the interoperable legacy-client group
// with system-generated DIRECT-* credentials.
manager.createGroup(channel, createListener)
}
} catch (e: Exception) {
fallback("启动兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
}
}
// A stale persistent P2P group can keep old credentials or a 5 GHz
// channel. Remove it before creating this session's 2.4 GHz group.
try {
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
override fun onSuccess() = createGroup()
override fun onFailure(reason: Int) = createGroup()
})
} catch (_: Exception) {
createGroup()
}
}
@RequiresApi(29)
private fun compatibilityConfig(): WifiP2pConfig {
val random = ByteArray(12).also { SecureRandom().nextBytes(it) }
val token = random.joinToString("") { "%02x".format(it.toInt() and 0xff) }
return WifiP2pConfig.Builder()
.setNetworkName("DIRECT-QF-QFT${token.take(6)}")
.setPassphrase(token.take(16))
.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_2GHZ)
.build()
} }
@RequiresApi(26) @RequiresApi(26)
@Suppress("MissingPermission", "DEPRECATION") @Suppress("MissingPermission", "DEPRECATION")
private fun startApi26( private fun startLocalOnlyHotspot(
run: Int, run: Int,
onStarted: (WifiCredentials) -> Unit, onStarted: (WifiCredentials) -> Unit,
onFailed: (String) -> Unit, onFailed: (String) -> Unit,
@@ -57,7 +194,7 @@ class PhoneHotspotController(context: Context) {
val passphrase = identity.second.orEmpty() val passphrase = identity.second.orEmpty()
if (ssid.isBlank() || passphrase.length !in 8..63) { if (ssid.isBlank() || passphrase.length !in 8..63) {
close() close()
onFailed("系统临时热点没有返回有效的名称或密码") onFailed("系统备用热点没有返回有效的名称或密码")
return return
} }
onStarted(WifiCredentials(ssid, passphrase, identity.third)) onStarted(WifiCredentials(ssid, passphrase, identity.third))
@@ -66,26 +203,31 @@ class PhoneHotspotController(context: Context) {
override fun onStopped() { override fun onStopped() {
if (run == generation) { if (run == generation) {
reservation = null reservation = null
onFailed("系统已停止 QFT 临时热点") onFailed("系统已停止 QFT 备用临时热点")
} }
} }
override fun onFailed(reason: Int) { override fun onFailed(reason: Int) {
if (run == generation) { if (run == generation) onFailed("系统无法创建备用临时热点(错误 $reason)")
onFailed("系统无法创建临时热点(错误 $reason)")
}
} }
}, },
Handler(Looper.getMainLooper()), handler,
) )
} catch (e: Exception) { } catch (e: Exception) {
onFailed("启动临时热点失败:${e.message ?: e.javaClass.simpleName}") onFailed("启动备用临时热点失败:${e.message ?: e.javaClass.simpleName}")
} }
} }
@Suppress("MissingPermission")
fun close() { fun close() {
generation++ generation++
handler.removeCallbacksAndMessages(null)
try { reservation?.close() } catch (_: Exception) {} try { reservation?.close() } catch (_: Exception) {}
reservation = null reservation = null
val channel = p2pChannel
p2pChannel = null
if (channel != null) {
try { p2pManager?.removeGroup(channel, null) } catch (_: Exception) {}
}
} }
} }
@@ -6,6 +6,7 @@ import org.json.JSONObject
import java.io.BufferedInputStream import java.io.BufferedInputStream
import java.io.BufferedOutputStream import java.io.BufferedOutputStream
import java.io.FileInputStream import java.io.FileInputStream
import java.io.InputStream
import java.net.DatagramPacket import java.net.DatagramPacket
import java.net.DatagramSocket import java.net.DatagramSocket
import java.net.InetAddress import java.net.InetAddress
@@ -30,6 +31,24 @@ data class PhoneShareManifestItem(
val path: String, val path: String,
) )
/** Hash exactly the advertised number of bytes and reject stale provider size
* metadata. The manifest and Range server must describe the identical snapshot. */
internal fun phoneShareSha256Exact(input: InputStream, expectedSize: Long): String {
require(expectedSize >= 0L)
val digest = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(1024 * 1024)
var remaining = expectedSize
while (remaining > 0L) {
val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
require(count >= 0) { "实际内容小于文件选择器报告的大小" }
if (count == 0) continue
digest.update(buffer, 0, count)
remaining -= count.toLong()
}
require(input.read() < 0) { "实际内容大于文件选择器报告的大小" }
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
}
internal fun phoneShareRange(value: String?, size: Long): Pair<Long, Long>? { internal fun phoneShareRange(value: String?, size: Long): Pair<Long, Long>? {
if (size == 0L) return if (value == null) 0L to 0L else null if (size == 0L) return if (value == null) 0L to 0L else null
if (value == null) return 0L to (size - 1L) if (value == null) return 0L to (size - 1L)
@@ -276,16 +295,17 @@ class PhoneShareServer private constructor(
value.none { it.code <= 31 || it.code == 127 || it in "\\/:*?\"<>|" } value.none { it.code <= 31 || it.code == 127 || it in "\\/:*?\"<>|" }
private fun sha256(resolver: ContentResolver, file: SelectedFile): String { private fun sha256(resolver: ContentResolver, file: SelectedFile): String {
val digest = MessageDigest.getInstance("SHA-256") val source = resolver.openInputStream(file.uri) ?: error("无法读取 ${file.name}")
resolver.openInputStream(file.uri)?.use { input -> return source.use { input ->
val buffer = ByteArray(1024 * 1024) // Hash exactly the bytes that the Range server will expose.
while (true) { // Reject mutable/stale provider metadata instead of producing a
val count = input.read(buffer) // QR whose manifest hash can never match the advertised size.
if (count < 0) break try {
if (count > 0) digest.update(buffer, 0, count) phoneShareSha256Exact(input, file.size)
} catch (e: IllegalArgumentException) {
error("${file.name}:${e.message},请重新选择")
}
} }
} ?: error("无法读取 ${file.name}")
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
} }
private fun readLine(input: BufferedInputStream): String? { private fun readLine(input: BufferedInputStream): String? {
@@ -4,12 +4,28 @@ import org.junit.Assert.*
import org.junit.Test import org.junit.Test
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.nio.ByteOrder import java.nio.ByteOrder
import java.io.ByteArrayInputStream
import java.util.concurrent.Callable import java.util.concurrent.Callable
import java.util.concurrent.ExecutorCompletionService import java.util.concurrent.ExecutorCompletionService
import java.util.concurrent.Executors import java.util.concurrent.Executors
import java.util.zip.CRC32 import java.util.zip.CRC32
class ProtocolTest { class ProtocolTest {
@Test
fun phoneShareHashRequiresTheAdvertisedExactSize() {
val bytes = "phone-share-stable-snapshot".toByteArray()
assertEquals(
"83511688f11a9cb98da9339966f6a0b97e48913102aaad39ae395d2e88f3f65f",
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong()),
)
assertThrows(IllegalArgumentException::class.java) {
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() + 1L)
}
assertThrows(IllegalArgumentException::class.java) {
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() - 1L)
}
}
@Test @Test
fun directDiscoveryCarriesTheAndroidDeviceName() { fun directDiscoveryCarriesTheAndroidDeviceName() {
val request = directDiscoveryRequest( val request = directDiscoveryRequest(
+8 -7
View File
@@ -1,4 +1,4 @@
# Android → Android 真机验收(v0.5.0-dev3) # Android → Android 真机验收(v0.5.0-dev4)
## 构建约束 ## 构建约束
@@ -11,7 +11,7 @@ cd android
## 首轮验收 ## 首轮验收
1. 两台 Android 安装同一个 `v0.5.0-dev3` APK。 1. 两台 Android 安装同一个 `v0.5.0-dev4` APK。
2. 发送手机进入“手机 → 手机”,选择至少两个文件并调整一次顺序。 2. 发送手机进入“手机 → 手机”,选择至少两个文件并调整一次顺序。
3. 点击“创建发送二维码”,允许附近 Wi-Fi/位置权限。 3. 点击“创建发送二维码”,允许附近 Wi-Fi/位置权限。
4. 接收手机进入“扫码直传”,扫描发送手机二维码并确认系统连接提示。 4. 接收手机进入“扫码直传”,扫描发送手机二维码并确认系统连接提示。
@@ -21,11 +21,12 @@ cd android
## 必测网络组合 ## 必测网络组合
- Android 13+ → Android 13+:`NEARBY_WIFI_DEVICES` 权限与临时热点。 - Android 13+ → Android 13+:`NEARBY_WIFI_DEVICES` 权限与 2.4 GHz/WPA2 Wi-Fi Direct 兼容接入点。
- Android 13+ 发送 → Android 7–9 接收:连续停止并重建两次发送热点;旧机每次均应使用二维码中的最新密码连接,不得复用同名热点旧凭据。 - Android 13+ 发送 → Android 7–9 接收:旧机应能看到 `DIRECT-*` 专用网络;连续停止并重建两次,旧机每次均使用二维码中的最新密码连接。
- Android 13+ 发送 → Android 10–12 接收:新会话即使复用了热点名称,只要密码变化就必须创建新的系统配网请求。 - Android 13+ 发送 → Android 10–12 接收:新会话即使复用了热点名称,只要密码变化就必须创建新的系统配网请求。
- 高版本发送端返回纯 WPA3、旧接收机不支持 SAE:应立即转入原局域网自动探测,不应停留在系统热点搜索。 - Wi-Fi Direct 被 OEM 禁用:发送端自动回落 LocalOnlyHotspot;纯 WPA3 且接收机不支持 SAE 时自动尝试原局域网,不应无限搜索。
- Android 7 发送端:两机先连接同一 Wi-Fi,验证自动 LAN 回落。 - Android 7–9 发送 → Android 13+ 接收:至少传输一个 100 MiB 文件两次,均通过 SHA-256,不得再出现整文件重下后仍校验失败。
- Android 7 发送端:验证系统生成的 `DIRECT-*` WPA2 组可被高版本接收端自动加入;P2P 创建失败时再验证同局域网回落。
- 手动停止发送端热点:接收端应报连接中断,而不是无限等待。 - 手动停止发送端热点:接收端应报连接中断,而不是无限等待。
- 传输中返回发送端首页:服务和临时热点应立即关闭。 - 传输中返回发送端首页:服务和临时热点应立即关闭。
@@ -39,5 +40,5 @@ cd android
- 仅文件,不包含文件夹。 - 仅文件,不包含文件夹。
- 发送与接收页面需保持前台;尚未引入前台服务。 - 发送与接收页面需保持前台;尚未引入前台服务。
- LocalOnlyHotspot 没有互联网是预期行为,文件只在本地链路传输。 - Wi-Fi Direct/LocalOnlyHotspot 没有互联网是预期行为,文件只在本地链路传输。
- Android ↔ iOS 不在本开发版本范围内。 - Android ↔ iOS 不在本开发版本范围内。
+10 -7
View File
@@ -99,10 +99,10 @@ The sender returns `206 Partial Content`, the matching `Content-Range`, and the
For both direct-transfer directions, the Windows listener may accept connections non-blockingly for shutdown responsiveness, but each accepted file socket is switched to blocking I/O with explicit timeouts before reading or writing request bodies. This prevents `WSAEWOULDBLOCK (10035)` from turning an in-progress parallel transfer into an HTTP 500 failure. For both direct-transfer directions, the Windows listener may accept connections non-blockingly for shutdown responsiveness, but each accepted file socket is switched to blocking I/O with explicit timeouts before reading or writing request bodies. This prevents `WSAEWOULDBLOCK (10035)` from turning an in-progress parallel transfer into an HTTP 500 failure.
## 6. Android → Android (`QFTPHONE2`, v0.5.0-dev3) ## 6. Android → Android (`QFTPHONE2`, v0.5.0-dev4)
The sender starts an authenticated local HTTP service and encodes only session, The sender starts an authenticated local HTTP service and encodes only session,
port, sender identity and optional LocalOnlyHotspot credentials in the QR. The port, sender identity and optional dedicated-network credentials in the QR. The
file queue is fetched after pairing so QR density is independent of queue size: file queue is fetched after pairing so QR density is independent of queue size:
```text ```text
@@ -117,8 +117,11 @@ The manifest contains a bounded ordered list of `name`, `size`, `sha256` and a
server-generated fixed download path. The receiver does not accept arbitrary server-generated fixed download path. The receiver does not accept arbitrary
paths from the QR or manifest: entry `N` must use `/qft/phone/download/N`. paths from the QR or manifest: entry `N` must use `/qft/phone/download/N`.
Android 8+ prefers a system LocalOnlyHotspot. Android 7, or a hotspot failure, Android prefers a 2.4 GHz WPA2 Wi-Fi Direct group-owner AP that accepts legacy
falls back to literal private IPv4 endpoints on the current LAN. WPA2/WPA3 Wi-Fi stations. An OEM P2P failure falls back to LocalOnlyHotspot, then literal
credentials are distinguished in `w[2]`. The receiver then reuses the existing private IPv4 endpoints on the current LAN. WPA2/WPA3
parallel Range ledger, retries and SHA-256-before-publish behavior for every credentials are distinguished in `w[2]`. The receiver reuses the existing Range
file, processing items in manifest order. ledger, retries and SHA-256-before-publish behavior for every file, processing
items in manifest order. Phone senders use one deterministic Range worker to
avoid concurrent-read corruption in older Android document providers; desktop
senders retain up to eight workers.
+5 -1
View File
@@ -13,6 +13,7 @@ gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text()
assert re.search(r'minSdk\s*=\s*24',gradle) assert re.search(r'minSdk\s*=\s*24',gradle)
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest and 'NEARBY_WIFI_DEVICES' in manifest assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest and 'NEARBY_WIFI_DEVICES' in manifest
assert 'android.hardware.wifi.direct' in manifest
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
@@ -27,9 +28,12 @@ assert 'unsupportedHotspot' in main and 'pair.copy(wifi = null)' in main
assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload
assert 'awaitGatewayEndpoints' not in main assert 'awaitGatewayEndpoints' not in main
assert 'QFTPHONE2:' in (ROOT/'android/app/src/main/java/com/qft/optical/PairingProtocol.kt').read_text() assert 'QFTPHONE2:' in (ROOT/'android/app/src/main/java/com/qft/optical/PairingProtocol.kt').read_text()
assert 'startLocalOnlyHotspot' in phone_hotspot and 'PhoneShareServer.create' in main assert 'WifiP2pManager' in phone_hotspot and 'createGroup' in phone_hotspot
assert 'GROUP_OWNER_BAND_2GHZ' in phone_hotspot and 'setNetworkName("DIRECT-QF-' in phone_hotspot
assert 'startLocalOnlyHotspot' in phone_hotspot and 'Build.VERSION.SDK_INT < 26' not in main
assert '/qft/phone/manifest' in phone_server and '/qft/phone/download/' in phone_server assert '/qft/phone/manifest' in phone_server and '/qft/phone/download/' in phone_server
assert 'startDownloadsFromPhone' in main and 'downloadPath = item.path' in main assert 'startDownloadsFromPhone' in main and 'downloadPath = item.path' in main
assert 'downloadPath.startsWith("/qft/phone/download/")' in download and 'else RANGE_WORKERS' in download
assert 'phoneQrSidePx(windowWidth, windowHeight' in main assert 'phoneQrSidePx(windowWidth, windowHeight' in main
assert 'LinearLayout.LayoutParams(qrSide, qrSide)' in main assert 'LinearLayout.LayoutParams(qrSide, qrSide)' in main
assert 'PhoneQr.render(encoded, 720)' not in main assert 'PhoneQr.render(encoded, 720)' not in main
+1
View File
@@ -45,6 +45,7 @@ assert 'const val PREFIX_PHONE_V2 = "QFTPHONE2:"' in pairing
assert '"m" -> TransferDirection.PHONE_TO_PHONE' in pairing assert '"m" -> TransferDirection.PHONE_TO_PHONE' in pairing
assert 'require(item.getString("path") == expectedPath)' in server assert 'require(item.getString("path") == expectedPath)' in server
assert 'headers["x-qft-token"] != session' in server assert 'headers["x-qft-token"] != session' in server
assert 'phoneShareSha256Exact' in server and 'require(input.read() < 0)' in server
assert 'Range: bytes=<start>-<end>' not in server # implementation, not documentation placeholder assert 'Range: bytes=<start>-<end>' not in server # implementation, not documentation placeholder
assert 'baseUrl + pairing.downloadPath' in download assert 'baseUrl + pairing.downloadPath' in download
assert 'digest(downloadPath.toByteArray' in download assert 'digest(downloadPath.toByteArray' in download