AndroidStation(原中控改造为纯设备端) - 只做三件事:UDP 48899 被桌面端发现、TCP 8087 推送 USB 扫码结果、离线语音播报 - 扫码不再经过 UI:去掉逐键重绘,50ms 自动提交,同一码重复扫码也一律上报 - 离线语音种子(数字/字母/“开始打包”/欢迎语)随包安装,MediaPlayer 播放,启动把音量拉满 - 启动播报「欢迎使用溯源系统,初始化已经完成,扫码即可开始打包」 - 移除 Device Owner / 设备管理员 / lock task / 网络与 IP 设置等非普通应用能力(仅保留开机自启) - 正式签名 keystore + release 签名配置,versionName/versionCode 可由打包脚本覆盖 发布脚手架 - backend/android_client:Android 正式包构建(build.ps1 + package.config.json) - backend/scripts/deploy/publish-android.cjs + npm run android:build / android:publish - 桌面端安装包改为 download/desktop,Android 为 download/android_client; version.json 仍走 /download/version.json(老客户端写死),新增 /download/android_client/version.json - 谷歌插件随桌面端 MSI 安装到 <安装目录>\extension,工具菜单新增「复制谷歌插件地址」 - git-safety-check 增加仓库级禁区(keystore.properties / *.jks / local.properties) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
476 lines
16 KiB
PowerShell
476 lines
16 KiB
PowerShell
<#
|
||
.SYNOPSIS
|
||
AndroidStation 设备端真机调试脚手架:构建 / 装机 / 启动 / 抓日志。
|
||
|
||
.DESCRIPTION
|
||
约定:薄入口 + 厚实现。所有逻辑都在本脚本里,.vscode/tasks.json 与命令行只做转发。
|
||
|
||
已内置处理(都是本机 / 本设备实际踩过的坑):
|
||
- JAVA_HOME 自动探测(本机 java 不在 PATH)
|
||
- adb 自动探测(不在 PATH)
|
||
- 多设备自动记住上次选择(.dev-adb.local.json,不入库)
|
||
- adb install 失败自动降级为 push + pm install(老盒子报 fork failed)
|
||
- 启动依次尝试 am start / am start(LEANBACK) / monkey,全失败时明确提示手动启动
|
||
- logcat 只跟随本应用 tag,并附带 AndroidRuntime:E 以便看到崩溃
|
||
- 设备端只建 UDP/TCP socket,普通装 /data 即可,不需要系统应用权限
|
||
|
||
.EXAMPLE
|
||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 dev
|
||
|
||
.EXAMPLE
|
||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 install -Serial 4235737
|
||
#>
|
||
[CmdletBinding()]
|
||
param(
|
||
[Parameter(Position = 0)]
|
||
[ValidateSet('build', 'install', 'run', 'dev', 'logs', 'clean', 'devices', 'help')]
|
||
[string]$Task = 'help',
|
||
|
||
[ValidateSet('debug', 'release')]
|
||
[string]$Variant = 'debug',
|
||
|
||
[string]$Serial = '',
|
||
|
||
[switch]$CleanFirst,
|
||
[switch]$NoLaunch,
|
||
[switch]$NoLogcat
|
||
)
|
||
|
||
$ErrorActionPreference = 'Stop'
|
||
|
||
# ============================ 常量 ============================
|
||
|
||
$ProjectRoot = Split-Path -Parent $PSScriptRoot
|
||
$PackageName = 'com.gztbyc.scancenter'
|
||
$ActivityName = "$PackageName/.MainActivity"
|
||
$LogTag = 'AndroidStation'
|
||
$StateFile = Join-Path $ProjectRoot '.dev-adb.local.json'
|
||
$LocalProps = Join-Path $ProjectRoot 'local.properties'
|
||
|
||
# ============================ 输出 ============================
|
||
|
||
function Write-Step([string]$Message) { Write-Host "[android] $Message" -ForegroundColor Cyan }
|
||
function Write-Ok([string]$Message) { Write-Host "[android] OK $Message" -ForegroundColor Green }
|
||
function Write-Warn([string]$Message) { Write-Host "[android] !! $Message" -ForegroundColor Yellow }
|
||
|
||
# ============================ 外部命令封装 ============================
|
||
|
||
# 统一调用外部程序:不因 stderr 输出而抛异常,并返回退出码与合并后的文本
|
||
function Invoke-Native {
|
||
param(
|
||
[Parameter(Mandatory = $true)][string]$FilePath,
|
||
[string[]]$Arguments = @(),
|
||
[switch]$Quiet
|
||
)
|
||
|
||
$previous = $ErrorActionPreference
|
||
$ErrorActionPreference = 'Continue'
|
||
try {
|
||
if ($Quiet) {
|
||
$output = & $FilePath @Arguments 2>&1
|
||
$text = ($output | Out-String)
|
||
return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $text }
|
||
}
|
||
|
||
& $FilePath @Arguments
|
||
return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = '' }
|
||
}
|
||
finally {
|
||
$ErrorActionPreference = $previous
|
||
}
|
||
}
|
||
|
||
# ============================ 环境探测 ============================
|
||
|
||
function Resolve-JavaHome {
|
||
if ($env:JAVA_HOME) {
|
||
if (Test-Path (Join-Path $env:JAVA_HOME 'bin\java.exe')) { return $env:JAVA_HOME }
|
||
}
|
||
|
||
$roots = @()
|
||
if ($env:LOCALAPPDATA) { $roots += (Join-Path $env:LOCALAPPDATA 'Programs\EclipseAdoptium') }
|
||
$roots += 'C:\Program Files\Eclipse Adoptium'
|
||
$roots += 'C:\Program Files\Java'
|
||
|
||
foreach ($root in $roots) {
|
||
if (-not (Test-Path $root)) { continue }
|
||
$jdk = Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
|
||
Where-Object { Test-Path (Join-Path $_.FullName 'bin\java.exe') } |
|
||
Sort-Object Name -Descending |
|
||
Select-Object -First 1
|
||
if ($jdk) { return $jdk.FullName }
|
||
}
|
||
return ''
|
||
}
|
||
|
||
function Resolve-SdkDir {
|
||
if (Test-Path $LocalProps) {
|
||
$match = Select-String -Path $LocalProps -Pattern '^\s*sdk\.dir\s*=' -ErrorAction SilentlyContinue | Select-Object -First 1
|
||
if ($match) {
|
||
# local.properties 里的 Windows 路径是转义写法(C\:\\Users\\...),需要还原
|
||
return ($match.Line -split '=', 2)[1].Trim().Replace('\:', ':').Replace('\\', '\')
|
||
}
|
||
}
|
||
if ($env:ANDROID_HOME) { return $env:ANDROID_HOME }
|
||
if ($env:ANDROID_SDK_ROOT) { return $env:ANDROID_SDK_ROOT }
|
||
if ($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA 'Android\Sdk') }
|
||
return ''
|
||
}
|
||
|
||
function Resolve-Adb {
|
||
$candidates = @()
|
||
$sdk = Resolve-SdkDir
|
||
if ($sdk) { $candidates += (Join-Path $sdk 'platform-tools\adb.exe') }
|
||
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Android\Sdk\platform-tools\adb.exe') }
|
||
|
||
foreach ($candidate in $candidates) {
|
||
if (Test-Path $candidate) { return $candidate }
|
||
}
|
||
# 退回 PATH
|
||
$onPath = Get-Command adb.exe -ErrorAction SilentlyContinue
|
||
if ($onPath) { return $onPath.Source }
|
||
throw '未找到 adb.exe,请确认 Android SDK platform-tools 已安装'
|
||
}
|
||
|
||
$Adb = $null
|
||
function Get-Adb {
|
||
if (-not $script:Adb) { $script:Adb = Resolve-Adb }
|
||
return $script:Adb
|
||
}
|
||
|
||
# ============================ 设备选择(含记忆) ============================
|
||
|
||
function Get-ConnectedDevices {
|
||
$adb = Get-Adb
|
||
$result = Invoke-Native $adb @('devices', '-l') -Quiet
|
||
$devices = @()
|
||
$abnormal = @()
|
||
|
||
foreach ($line in ($result.Output -split "`r?`n")) {
|
||
if ($line -match '^(\S+)\s+(device|unauthorized|offline|no permissions)\b\s*(.*)$') {
|
||
if ($Matches[2] -eq 'device') {
|
||
$devices += [pscustomobject]@{ Serial = $Matches[1]; Desc = $Matches[3].Trim() }
|
||
}
|
||
else {
|
||
$abnormal += "$($Matches[1]) [$($Matches[2])]"
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($abnormal.Count -gt 0) {
|
||
Write-Warn ("下列设备状态异常:" + ($abnormal -join ','))
|
||
}
|
||
return $devices
|
||
}
|
||
|
||
function Read-SavedSerial {
|
||
if (-not (Test-Path $StateFile)) { return '' }
|
||
try { return (Get-Content $StateFile -Raw | ConvertFrom-Json).serial } catch { return '' }
|
||
}
|
||
|
||
function Save-Serial([string]$Value) {
|
||
$json = "{`r`n `"serial`": `"$Value`"`r`n}`r`n"
|
||
try {
|
||
# 不写 BOM,避免其它工具解析 JSON 出错
|
||
[System.IO.File]::WriteAllText($StateFile, $json, (New-Object System.Text.UTF8Encoding($false)))
|
||
}
|
||
catch {
|
||
# 写入失败不影响主流程
|
||
}
|
||
}
|
||
|
||
function Select-Device {
|
||
if ($Serial) {
|
||
Save-Serial $Serial
|
||
return $Serial
|
||
}
|
||
|
||
$devices = @(Get-ConnectedDevices)
|
||
if ($devices.Count -eq 0) {
|
||
throw '未检测到已连接设备。请检查 USB / 无线调试,或执行 adb devices 确认。'
|
||
}
|
||
|
||
$saved = Read-SavedSerial
|
||
if ($saved) {
|
||
foreach ($device in $devices) {
|
||
if ($device.Serial -eq $saved) {
|
||
Write-Step "使用上次选择的设备:$($device.Serial) $($device.Desc)(可用 -Serial 更换)"
|
||
return $device.Serial
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($devices.Count -eq 1) {
|
||
Save-Serial $devices[0].Serial
|
||
Write-Step "使用设备:$($devices[0].Serial) $($devices[0].Desc)"
|
||
return $devices[0].Serial
|
||
}
|
||
|
||
Write-Host '[android] 检测到多台设备:' -ForegroundColor Cyan
|
||
for ($i = 0; $i -lt $devices.Count; $i++) {
|
||
Write-Host (" [{0}] {1} {2}" -f ($i + 1), $devices[$i].Serial, $devices[$i].Desc)
|
||
}
|
||
|
||
if (-not $Host.Name -or [Console]::IsInputRedirected) {
|
||
throw "多台设备时请用 -Serial 指定,例如:-Serial $($devices[0].Serial)"
|
||
}
|
||
|
||
$answer = Read-Host "请选择设备序号 [1-$($devices.Count)],直接回车取 1"
|
||
$index = 0
|
||
if ($answer) { $index = [int]$answer - 1 }
|
||
if ($index -lt 0 -or $index -ge $devices.Count) { throw "无效序号:$answer" }
|
||
|
||
Save-Serial $devices[$index].Serial
|
||
return $devices[$index].Serial
|
||
}
|
||
|
||
# ============================ 构建 ============================
|
||
|
||
function Invoke-Gradle {
|
||
param([string[]]$Arguments)
|
||
|
||
$javaHome = Resolve-JavaHome
|
||
if ($javaHome) {
|
||
$env:JAVA_HOME = $javaHome
|
||
Write-Step "JAVA_HOME = $javaHome"
|
||
}
|
||
else {
|
||
Write-Warn '未探测到 JDK,若构建失败请手动设置 JAVA_HOME'
|
||
}
|
||
|
||
$gradlew = Join-Path $ProjectRoot 'gradlew.bat'
|
||
if (-not (Test-Path $gradlew)) { throw "未找到 gradlew.bat:$gradlew" }
|
||
|
||
Write-Step ("gradlew " + ($Arguments -join ' '))
|
||
$result = Invoke-Native $gradlew $Arguments
|
||
if ($result.ExitCode -ne 0) { throw "构建失败(gradlew 退出码 $($result.ExitCode))" }
|
||
}
|
||
|
||
function Get-ApkPath {
|
||
$dir = Join-Path $ProjectRoot "app\build\outputs\apk\$Variant"
|
||
$expected = Join-Path $dir "app-$Variant.apk"
|
||
if (Test-Path $expected) { return $expected }
|
||
|
||
if (Test-Path $dir) {
|
||
$latest = Get-ChildItem -Path $dir -Filter '*.apk' -ErrorAction SilentlyContinue |
|
||
Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||
if ($latest) { return $latest.FullName }
|
||
}
|
||
throw "未找到 APK:$expected"
|
||
}
|
||
|
||
function Invoke-Build {
|
||
if ($CleanFirst) { Invoke-Gradle @('clean', '--console=plain') }
|
||
|
||
$variantCap = $Variant.Substring(0, 1).ToUpper() + $Variant.Substring(1)
|
||
Invoke-Gradle @(":app:assemble$variantCap", '--console=plain')
|
||
|
||
$apk = Get-ApkPath
|
||
$size = [math]::Round((Get-Item $apk).Length / 1MB, 2)
|
||
Write-Ok "APK = $apk ($size MB)"
|
||
return $apk
|
||
}
|
||
|
||
# ============================ 装机 ============================
|
||
|
||
function Install-Apk {
|
||
param([string]$TargetSerial, [string]$Apk)
|
||
|
||
$adb = Get-Adb
|
||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||
Write-Step "adb install -r(第 $attempt/3 次)"
|
||
$result = Invoke-Native $adb @('-s', $TargetSerial, 'install', '-r', $Apk) -Quiet
|
||
Write-Host $result.Output.TrimEnd()
|
||
if ($result.ExitCode -eq 0) {
|
||
Write-Ok '安装成功'
|
||
return
|
||
}
|
||
if ($attempt -lt 3) { Start-Sleep -Seconds 2 }
|
||
}
|
||
|
||
# 老盒子(Android 7.1.2 等)的流式安装常报 fork failed,改用两段式
|
||
Write-Warn 'adb install 连续失败,降级为 push + pm install'
|
||
$remote = '/data/local/tmp/' + [System.IO.Path]::GetFileName($Apk)
|
||
$push = Invoke-Native $adb @('-s', $TargetSerial, 'push', $Apk, $remote) -Quiet
|
||
Write-Host $push.Output.TrimEnd()
|
||
if ($push.ExitCode -ne 0) { throw '推送到设备失败' }
|
||
|
||
$install = Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'pm', 'install', '-r', $remote) -Quiet
|
||
Write-Host $install.Output.TrimEnd()
|
||
Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'rm', '-f', $remote) -Quiet | Out-Null
|
||
|
||
if ($install.Output -notmatch 'Success') { throw 'pm install 失败,请查看上方设备输出' }
|
||
Write-Ok '安装成功(push + pm install)'
|
||
}
|
||
|
||
# ============================ 预置成系统应用 ============================
|
||
|
||
# ============================ 启动 ============================
|
||
|
||
function Start-App {
|
||
param([string]$TargetSerial)
|
||
|
||
$adb = Get-Adb
|
||
Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'am', 'force-stop', $PackageName) -Quiet | Out-Null
|
||
|
||
$attempts = @(
|
||
[pscustomobject]@{
|
||
Name = 'am start -n'
|
||
Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-n', $ActivityName)
|
||
Expect = 'Starting:'
|
||
},
|
||
[pscustomobject]@{
|
||
Name = 'am start (LEANBACK)'
|
||
Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN',
|
||
'-c', 'android.intent.category.LEANBACK_LAUNCHER', '-n', $ActivityName)
|
||
Expect = 'Starting:'
|
||
},
|
||
[pscustomobject]@{
|
||
Name = 'monkey'
|
||
Args = @('-s', $TargetSerial, 'shell', 'monkey', '-p', $PackageName,
|
||
'-c', 'android.intent.category.LAUNCHER', '1')
|
||
Expect = 'Events injected'
|
||
}
|
||
)
|
||
|
||
foreach ($attempt in $attempts) {
|
||
$result = Invoke-Native $adb $attempt.Args -Quiet
|
||
if ($result.ExitCode -eq 0 -and $result.Output -match [regex]::Escape($attempt.Expect)) {
|
||
Write-Ok "已启动应用($($attempt.Name))"
|
||
return $true
|
||
}
|
||
|
||
$firstLine = ($result.Output -split "`r?`n" | Where-Object { $_.Trim() } | Select-Object -First 1)
|
||
Write-Warn "$($attempt.Name) 未成功:$firstLine"
|
||
}
|
||
|
||
Write-Warn '自动启动失败。部分海思/定制固件的 am 与 monkey 都会报 AMS 空指针,'
|
||
Write-Warn '本机无法绕过,请用遥控器手动打开「扫描中心」。'
|
||
return $false
|
||
}
|
||
|
||
# ============================ 日志 ============================
|
||
|
||
function Start-Logcat {
|
||
param([string]$TargetSerial)
|
||
|
||
$adb = Get-Adb
|
||
Invoke-Native $adb @('-s', $TargetSerial, 'logcat', '-c') -Quiet | Out-Null
|
||
|
||
Write-Step "跟随日志中(tag=$LogTag,含崩溃栈),Ctrl+C 退出"
|
||
Write-Host ("[android] 单独抓取:`"$adb`" -s $TargetSerial logcat -v time $LogTag`:V AndroidRuntime:E `*:S") -ForegroundColor DarkGray
|
||
|
||
$previous = $ErrorActionPreference
|
||
$ErrorActionPreference = 'Continue'
|
||
try {
|
||
& $adb -s $TargetSerial logcat -v time "$($LogTag):V" 'AndroidRuntime:E' '*:S'
|
||
}
|
||
finally {
|
||
$ErrorActionPreference = $previous
|
||
}
|
||
}
|
||
|
||
# ============================ 帮助 ============================
|
||
|
||
function Show-Help {
|
||
Write-Host @'
|
||
AndroidStation 设备端真机调试脚手架
|
||
|
||
用法:
|
||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 <任务> [选项]
|
||
|
||
任务:
|
||
build 仅构建 APK
|
||
install 构建 + 安装
|
||
run 构建 + 安装 + 启动
|
||
dev 构建 + 安装 + 启动 + 跟随日志(日常开发用这个)
|
||
logs 只跟随日志(不构建)
|
||
clean 清理构建产物
|
||
devices 列出已连接设备与当前记住的设备
|
||
help 显示本帮助
|
||
|
||
选项:
|
||
-Variant debug|release 构建类型,默认 debug
|
||
-Serial <序列号> 指定设备(默认自动选择,多设备时记住上次选择)
|
||
-CleanFirst 构建前先执行 gradle clean(全量重编)
|
||
-NoLaunch 不自动启动应用
|
||
-NoLogcat 不跟随日志
|
||
|
||
示例:
|
||
... -File tools\android.ps1 dev
|
||
... -File tools\android.ps1 install -Serial 4235737
|
||
... -File tools\android.ps1 dev -CleanFirst
|
||
... -File tools\android.ps1 run -Variant release
|
||
'@
|
||
}
|
||
|
||
function Show-Devices {
|
||
$devices = @(Get-ConnectedDevices)
|
||
$saved = Read-SavedSerial
|
||
|
||
if ($devices.Count -eq 0) {
|
||
Write-Warn '未检测到已连接设备'
|
||
return
|
||
}
|
||
|
||
Write-Host '[android] 已连接设备:' -ForegroundColor Cyan
|
||
foreach ($device in $devices) {
|
||
$mark = ''
|
||
if ($saved -and $device.Serial -eq $saved) { $mark = ' <- 当前记住' }
|
||
Write-Host (" {0} {1}{2}" -f $device.Serial, $device.Desc, $mark)
|
||
}
|
||
}
|
||
|
||
# ============================ 主流程 ============================
|
||
|
||
Set-Location $ProjectRoot
|
||
|
||
try {
|
||
switch ($Task) {
|
||
'help' { Show-Help }
|
||
|
||
'devices' { Show-Devices }
|
||
|
||
'clean' {
|
||
Invoke-Gradle @('clean', '--console=plain')
|
||
Write-Ok '已清理'
|
||
}
|
||
|
||
'build' {
|
||
$apk = Invoke-Build
|
||
# 单独输出一遍路径到管道,便于其它脚本捕获
|
||
Write-Output $apk
|
||
}
|
||
|
||
'install' {
|
||
$apk = Invoke-Build
|
||
Install-Apk -TargetSerial (Select-Device) -Apk $apk
|
||
}
|
||
|
||
'run' {
|
||
$apk = Invoke-Build
|
||
$target = Select-Device
|
||
Install-Apk -TargetSerial $target -Apk $apk
|
||
if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
|
||
if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
|
||
}
|
||
|
||
'dev' {
|
||
$apk = Invoke-Build
|
||
$target = Select-Device
|
||
Install-Apk -TargetSerial $target -Apk $apk
|
||
if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
|
||
if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
|
||
else { Write-Ok '完成(-NoLogcat 未跟随日志)' }
|
||
}
|
||
|
||
'logs' {
|
||
Start-Logcat -TargetSerial (Select-Device)
|
||
}
|
||
}
|
||
}
|
||
catch {
|
||
Write-Host "[android] 失败:$($_.Exception.Message)" -ForegroundColor Red
|
||
exit 1
|
||
}
|