This commit is contained in:
fengge 2026-04-01 22:37:21 +08:00
parent 639fdf1760
commit 9ab25e0a2f
7 changed files with 182 additions and 41 deletions

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@ -11,8 +11,8 @@ android {
applicationId = "com.stand.standapp" applicationId = "com.stand.standapp"
minSdk = 24 minSdk = 24
targetSdk = 34 targetSdk = 34
versionCode = 1 versionCode = 2
versionName = "1.0.0" versionName = "1.0.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }

View File

@ -43,6 +43,19 @@
.log-item { margin-bottom: 4px; border-bottom: 1px solid #334155; padding-bottom: 2px; } .log-item { margin-bottom: 4px; border-bottom: 1px solid #334155; padding-bottom: 2px; }
.log-time { color: #94a3b8; margin-right: 5px; } .log-time { color: #94a3b8; margin-right: 5px; }
.log-msg { word-break: break-all; } .log-msg { word-break: break-all; }
/* Custom Modal Styles */
.modal-overlay {
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;
}
.modal-content {
background: white; padding: 20px; border-radius: 12px; width: 85%; max-width: 400px;
box-shadow: 0 10px 25px rgba(0,0,0,0.2);
}
.modal-header { font-weight: bold; font-size: 18px; margin-bottom: 15px; color: #004A8F; border-bottom: 1px solid #eee; padding-bottom: 10px; }
.modal-body { font-size: 14px; line-height: 1.8; color: #444; word-break: break-all; }
.modal-footer { margin-top: 20px; text-align: right; }
</style> </style>
</head> </head>
<body> <body>
@ -66,7 +79,8 @@
<p style="font-size: 12px; color: #666;">(适用于蓝牙/USB 小票机,传输原始 JSON)</p> <p style="font-size: 12px; color: #666;">(适用于蓝牙/USB 小票机,传输原始 JSON)</p>
<button class="btn btn-orange" onclick="callUpdate()">3. 检查系统更新</button> <button class="btn btn-orange" onclick="callUpdate()">3. 检查系统更新</button>
<button class="btn btn-red" onclick="callExit()">4. 退出应用</button> <button class="btn" style="background: #64748b;" onclick="callAbout()">4. 关于应用</button>
<button class="btn btn-red" onclick="callExit()">5. 退出应用</button>
<!-- WebSocket 控制区 --> <!-- WebSocket 控制区 -->
<div class="ws-card"> <div class="ws-card">
@ -177,6 +191,19 @@
Telewave SDK Connectivity v1.0 Telewave SDK Connectivity v1.0
</div> </div>
<!-- 自定义“关于”弹窗 -->
<div id="aboutModal" class="modal-overlay" onclick="closeAbout()">
<div class="modal-content" onclick="event.stopPropagation()">
<div class="modal-header">关于应用信息</div>
<div id="aboutBody" class="modal-body">
正在获取信息...
</div>
<div class="modal-footer">
<button class="btn" style="padding: 10px 20px; background: #64748b; margin: 0;" onclick="closeAbout()">确认</button>
</div>
</div>
</div>
<script> <script>
// 初始化界面 // 初始化界面
document.getElementById('current-time').innerText = new Date().toLocaleString(); document.getElementById('current-time').innerText = new Date().toLocaleString();
@ -239,6 +266,32 @@
} }
} }
function callAbout() {
if (window.android && window.android.getAboutInfo) {
const infoStr = window.android.getAboutInfo();
try {
const info = JSON.parse(infoStr);
const html = `
<strong>应用名称:</strong> ${info.appName}<br>
<strong>版本号:</strong> <span style="color: #3b82f6;">${info.versionName}</span><br>
<strong>设备型号:</strong> ${info.model}<br>
<strong>系统版本:</strong> Android ${info.osVersion}
`;
document.getElementById('aboutBody').innerHTML = html;
document.getElementById('aboutModal').style.display = 'flex';
} catch (e) {
document.getElementById('aboutBody').innerText = "获取信息解析失败: " + infoStr;
document.getElementById('aboutModal').style.display = 'flex';
}
} else {
alert("关于接口未就绪");
}
}
function closeAbout() {
document.getElementById('aboutModal').style.display = 'none';
}
// 安卓回调函数:退出确认时执行 // 安卓回调函数:退出确认时执行
function addExitText() { function addExitText() {
const tag = document.getElementById('inject-status'); const tag = document.getElementById('inject-status');
@ -258,6 +311,7 @@
let clientId = "WEB_" + Math.random().toString(36).substr(2, 9); let clientId = "WEB_" + Math.random().toString(36).substr(2, 9);
let heartbeatTimer = null; let heartbeatTimer = null;
let reconnectTimer = null; let reconnectTimer = null;
let isManualClose = false; // 新增:手动断开标记
const logList = document.getElementById('log-list'); const logList = document.getElementById('log-list');
document.getElementById('ws-client-id').innerText = clientId; document.getElementById('ws-client-id').innerText = clientId;
@ -301,6 +355,7 @@
const finalUrl = rawUrl.replace("{clientId}", clientId); const finalUrl = rawUrl.replace("{clientId}", clientId);
addLog("正在尝试连接: " + finalUrl, false); addLog("正在尝试连接: " + finalUrl, false);
isManualClose = false; // 启动连接时重置标记
try { try {
ws = new WebSocket(finalUrl); ws = new WebSocket(finalUrl);
@ -324,8 +379,12 @@
updateWSStatus(false); updateWSStatus(false);
addLog("连接关闭", false); addLog("连接关闭", false);
stopHeartbeat(); stopHeartbeat();
// 5秒后自动重连
reconnectTimer = setTimeout(connectWS, 5000); // 只有非手动断开(如网络异常)时才自动重连
if (!isManualClose) {
addLog("异常断开5秒后自动重连...", false);
reconnectTimer = setTimeout(connectWS, 5000);
}
}; };
ws.onerror = (err) => { ws.onerror = (err) => {
@ -339,6 +398,7 @@
function toggleWS() { function toggleWS() {
if (ws && ws.readyState === WebSocket.OPEN) { if (ws && ws.readyState === WebSocket.OPEN) {
isManualClose = true; // 标记为手动断开
clearTimeout(reconnectTimer); clearTimeout(reconnectTimer);
reconnectTimer = null; reconnectTimer = null;
ws.close(); ws.close();

View File

@ -46,14 +46,18 @@ class AndroidInterface(private val activity: MainActivity) {
*/ */
@JavascriptInterface @JavascriptInterface
fun printRawData(data: String) { fun printRawData(data: String) {
Log.d("Print", "收到 H5 原始打印数据: $data") try {
Handler(Looper.getMainLooper()).post { Log.d("Print", "收到 H5 原始打印数据: $data")
// 这里可以弹出一个选择框让用户选择打印机,或者根据配置自动连接 Handler(Looper.getMainLooper()).post {
// 常见的打印流程1. 解析数据 -> 2. 转换成 ESC/POS 指令 -> 3. 发送到通道 try {
Toast.makeText(activity, "H5指令打印: $data", Toast.LENGTH_LONG).show() // 这里可以弹出一个选择框让用户选择打印机,或者根据配置自动连接
Toast.makeText(activity, "H5指令打印: $data", Toast.LENGTH_SHORT).show()
// 预留不同通道的入口 } catch (e: Exception) {
// connectAndPrint(data) Log.e("Print", "Toast显示失败", e)
}
}
} catch (e: Exception) {
Log.e("Print", "指令解析失败", e)
} }
} }
@ -63,7 +67,11 @@ class AndroidInterface(private val activity: MainActivity) {
@JavascriptInterface @JavascriptInterface
fun startUpdate(apkUrl: String) { fun startUpdate(apkUrl: String) {
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
UpdateManager(activity).checkUpdate() try {
UpdateManager(activity).checkUpdate()
} catch (e: Exception) {
Log.e("Update", "启动更新检查失败", e)
}
} }
} }
@ -73,7 +81,12 @@ class AndroidInterface(private val activity: MainActivity) {
@JavascriptInterface @JavascriptInterface
fun exitApp() { fun exitApp() {
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
activity.showExitDialog() try {
activity.showExitDialog()
} catch (e: Exception) {
Log.e("App", "显示退出弹窗失败", e)
activity.finish()
}
} }
} }
@ -90,17 +103,39 @@ class AndroidInterface(private val activity: MainActivity) {
} }
} }
/**
* JS 调用获取关于信息
*/
@JavascriptInterface
fun getAboutInfo(): String {
return try {
val packageInfo = activity.packageManager.getPackageInfo(activity.packageName, 0)
val json = org.json.JSONObject()
json.put("appName", activity.getString(R.string.app_name))
json.put("versionName", packageInfo.versionName)
json.put("model", android.os.Build.MODEL)
json.put("osVersion", android.os.Build.VERSION.RELEASE)
json.toString()
} catch (e: Exception) {
"{ \"appName\": \"StandApp\", \"versionName\": \"1.0.0\" }"
}
}
/** /**
* JS 调用保存消息记录 * JS 调用保存消息记录
*/ */
@JavascriptInterface @JavascriptInterface
fun saveMessage(message: String) { fun saveMessage(message: String) {
val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE) try {
val currentMsgs = prefs.getString("history", "") ?: "" val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE)
val updatedMsgs = if (currentMsgs.isEmpty()) message else "$message|---|$currentMsgs" val currentMsgs = prefs.getString("history", "") ?: ""
// 限制保存最近5000条 val updatedMsgs = if (currentMsgs.isEmpty()) message else "$message|---|$currentMsgs"
val list = updatedMsgs.split("|---|").take(5000) // 限制保存最近5000条
prefs.edit().putString("history", list.joinToString("|---|")).apply() val list = updatedMsgs.split("|---|").take(5000)
prefs.edit().putString("history", list.joinToString("|---|")).apply()
} catch (e: Exception) {
Log.e("Storage", "消息保存异常", e)
}
} }
/** /**
@ -108,8 +143,12 @@ class AndroidInterface(private val activity: MainActivity) {
*/ */
@JavascriptInterface @JavascriptInterface
fun getMessages(): String { fun getMessages(): String {
val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE) return try {
return prefs.getString("history", "") ?: "" val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE)
prefs.getString("history", "") ?: ""
} catch (e: Exception) {
""
}
} }
/** /**
@ -117,7 +156,13 @@ class AndroidInterface(private val activity: MainActivity) {
*/ */
@JavascriptInterface @JavascriptInterface
fun clearMessages() { fun clearMessages() {
activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE).edit().clear().apply() try {
Toast.makeText(activity, "消息记录已清空", Toast.LENGTH_SHORT).show() activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE).edit().clear().apply()
Handler(Looper.getMainLooper()).post {
Toast.makeText(activity, "记录已清空", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
Log.e("Storage", "清空记录异常", e)
}
} }
} }

View File

@ -11,7 +11,7 @@ object AppConfig {
private const val KEY_PASSWORD = "saved_password" private const val KEY_PASSWORD = "saved_password"
// 默认服务器地址 // 默认服务器地址
const val DEFAULT_SERVER_URL = "http://152.32.186.199:38080" const val DEFAULT_SERVER_URL = "https://template.gyouzhe.com"
private fun getPrefs(context: Context): SharedPreferences { private fun getPrefs(context: Context): SharedPreferences {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

View File

@ -25,6 +25,8 @@ class MainActivity : AppCompatActivity() {
// 从配置中获取服务器地址 // 从配置中获取服务器地址
val serverUrl = AppConfig.getServerUrl(this) val serverUrl = AppConfig.getServerUrl(this)
val finalUrl = "$serverUrl/example/print_demo.html?t=\${System.currentTimeMillis()}"
Log.d("MainActivity", "Loading URL: $finalUrl")
mAgentWeb = AgentWeb.with(this) mAgentWeb = AgentWeb.with(this)
.setAgentWebParent(container, LinearLayout.LayoutParams(-1, -1)) .setAgentWebParent(container, LinearLayout.LayoutParams(-1, -1))
@ -32,7 +34,7 @@ class MainActivity : AppCompatActivity() {
.addJavascriptInterface("android", AndroidInterface(this)) .addJavascriptInterface("android", AndroidInterface(this))
.createAgentWeb() .createAgentWeb()
.ready() .ready()
.go("https://template.gyouzhe.com/example/print_demo.html?t=\${System.currentTimeMillis()}") .go(finalUrl)
// 配置 WebView 属性以支持 SSE 和跨域 // 配置 WebView 属性以支持 SSE 和跨域
mAgentWeb?.let { agent -> mAgentWeb?.let { agent ->

View File

@ -56,7 +56,7 @@ class UpdateManager(private val context: Context) {
} }
} catch (e: Exception) { 0 } } catch (e: Exception) { 0 }
val url = "$serverUrl/app-version/check-update?versionCode=$currentVersionCode" val url = "$serverUrl/api/app-version/check-update?versionCode=$currentVersionCode"
val client = OkHttpClient() val client = OkHttpClient()
val request = Request.Builder().url(url).build() val request = Request.Builder().url(url).build()
@ -67,26 +67,45 @@ class UpdateManager(private val context: Context) {
} }
override fun onResponse(call: Call, response: Response) { override fun onResponse(call: Call, response: Response) {
val body = response.body?.string() ?: return
try { try {
val body = response.body?.string() ?: throw IOException("返回内容为空")
if (!response.isSuccessful) {
handler.post { Toast.makeText(context, "更新检查失败: ${response.code}", Toast.LENGTH_SHORT).show() }
return
}
val json = JSONObject(body) val json = JSONObject(body)
if (json.getInt("code") == 0) { if (json.getInt("code") == 0) {
val data = json.optJSONObject("data") val data = json.optJSONObject("data")
if (data != null) { if (data != null) {
val newVersionCode = data.getInt("versionCode") val newVersionCode = data.optInt("versionCode", 0)
if (newVersionCode > currentVersionCode) { if (newVersionCode > currentVersionCode) {
val versionName = data.getString("versionName") val versionName = data.optString("versionName", "New")
val content = data.getString("updateContent") val content = data.optString("updateContent", "优化系统体验")
val id = data.getLong("id") val id = data.optLong("id", -1)
(context as? AppCompatActivity)?.runOnUiThread { if (id != -1L) {
showUpdateDialog(versionName, content, id) (context as? AppCompatActivity)?.runOnUiThread {
try {
showUpdateDialog(versionName, content, id)
} catch (e: Exception) {
Toast.makeText(context, "显示更新弹窗失败", Toast.LENGTH_SHORT).show()
}
}
} }
} else {
handler.post { Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show() }
} }
} else {
handler.post { Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show() }
} }
} else {
val msg = json.optString("msg", "未知错误")
handler.post { Toast.makeText(context, "更新服务提示: $msg", Toast.LENGTH_SHORT).show() }
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e("UpdateManager", "解析结果失败", e) Log.e("UpdateManager", "解析或处理更新结果失败", e)
handler.post { Toast.makeText(context, "更新信息解析失败", Toast.LENGTH_SHORT).show() }
} }
} }
}) })
@ -131,7 +150,7 @@ class UpdateManager(private val context: Context) {
override fun onFailure(call: Call, e: IOException) { override fun onFailure(call: Call, e: IOException) {
handler.post { handler.post {
progressDialog?.dismiss() progressDialog?.dismiss()
Toast.makeText(context, "连接服务器失败: ${e.message}", Toast.LENGTH_LONG).show() Toast.makeText(context, "连接服务器失败", Toast.LENGTH_SHORT).show()
} }
} }
@ -139,12 +158,21 @@ class UpdateManager(private val context: Context) {
if (!response.isSuccessful) { if (!response.isSuccessful) {
handler.post { handler.post {
progressDialog?.dismiss() progressDialog?.dismiss()
Toast.makeText(context, "下载失败: 错误码 ${response.code}", Toast.LENGTH_LONG).show() Toast.makeText(context, "下载失败: ${response.code}", Toast.LENGTH_SHORT).show()
} }
return return
} }
val body = response.body val body = response.body
if (body != null) saveFileToPublic(body) if (body != null) {
try {
saveFileToPublic(body)
} catch (e: Exception) {
handler.post {
progressDialog?.dismiss()
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
}
}
}
} }
}) })
} }