websocket测试
This commit is contained in:
parent
3fc27119f9
commit
65e7e8d29b
|
|
@ -22,6 +22,21 @@
|
|||
.status-offline { background: #FEE2E2; color: #991B1B; }
|
||||
.bill-preview { border: 1px dashed #aaa; padding: 15px; background: #fff; margin-top: 20px; }
|
||||
.footer { text-align: center; margin-top: 30px; font-size: 12px; color: #999; }
|
||||
.exit-notice { color: #ef4444; font-weight: bold; font-size: 12px; margin-top: 5px; }
|
||||
|
||||
/* WebSocket Styles */
|
||||
.ws-card { margin-top: 20px; border-top: 2px solid #eee; padding-top: 20px; }
|
||||
.ws-status { font-size: 12px; padding: 4px 8px; border-radius: 4px; margin-left: 10px; }
|
||||
.ws-connected { background: #dcfce7; color: #166534; }
|
||||
.ws-disconnected { background: #fee2e2; color: #991b1b; }
|
||||
.log-container {
|
||||
background: #1e293b; color: #f8fafc; padding: 10px;
|
||||
border-radius: 6px; font-family: monospace; font-size: 11px;
|
||||
max-height: 200px; overflow-y: auto; margin-top: 10px;
|
||||
}
|
||||
.log-item { margin-bottom: 4px; border-bottom: 1px solid #334155; padding-bottom: 2px; }
|
||||
.log-time { color: #94a3b8; margin-right: 5px; }
|
||||
.log-msg { word-break: break-all; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -47,6 +62,29 @@
|
|||
<button class="btn btn-orange" onclick="callUpdate()">3. 检查系统更新</button>
|
||||
<button class="btn btn-red" onclick="callExit()">4. 退出应用</button>
|
||||
|
||||
<!-- WebSocket 控制区 -->
|
||||
<div class="ws-card">
|
||||
<div style="display: flex; align-items: center; justify-content: space-between;">
|
||||
<strong>WebSocket 实时推送</strong>
|
||||
<span id="ws-status-tag" class="ws-status ws-disconnected">未连接</span>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 10px; font-size: 13px;">
|
||||
ID: <span id="ws-client-id" style="color: #6366f1;">-</span>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap;">
|
||||
<button class="btn btn-green" style="margin:0; flex:1; padding: 10px; min-width: 120px;" onclick="toggleWS()">连接/断开 WS</button>
|
||||
<button class="btn" style="margin:0; flex:1; padding: 10px; min-width: 120px; background: #6366f1;" onclick="manualAddRecord()">手动新增记录</button>
|
||||
<button class="btn btn-orange" style="margin:0; flex:1; padding: 10px; min-width: 120px;" onclick="loadHistory()">从终端同步</button>
|
||||
<button class="btn btn-red" style="margin:0; flex:1; padding: 10px; min-width: 120px; background: #991b1b;" onclick="clearHistory()">清空终端存储</button>
|
||||
</div>
|
||||
|
||||
<div id="log-list" class="log-container">
|
||||
<div class="log-item">等待连接...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bill-preview" id="printArea">
|
||||
<div style="text-align: center; font-weight: bold; font-size: 18px;">测试签收单</div>
|
||||
<hr>
|
||||
|
|
@ -188,8 +226,159 @@
|
|||
}
|
||||
}
|
||||
|
||||
// 安卓回调函数:退出确认时执行
|
||||
function addExitText() {
|
||||
const tag = document.getElementById('inject-status');
|
||||
if (tag) {
|
||||
const notice = document.createElement('div');
|
||||
notice.className = 'exit-notice';
|
||||
notice.innerText = "⚠️ 检测到退出尝试 (" + new Date().toLocaleTimeString() + ")";
|
||||
tag.parentNode.insertBefore(notice, tag.nextSibling);
|
||||
}
|
||||
}
|
||||
|
||||
// 延迟检测
|
||||
setTimeout(checkApp, 300);
|
||||
|
||||
// === WebSocket 逻辑 ===
|
||||
let ws = null;
|
||||
let wsUrl = "ws://152.32.186.199:38080/ws/";
|
||||
let clientId = "WEB_" + Math.random().toString(36).substr(2, 9);
|
||||
let heartbeatTimer = null;
|
||||
let reconnectTimer = null;
|
||||
const logList = document.getElementById('log-list');
|
||||
|
||||
document.getElementById('ws-client-id').innerText = clientId;
|
||||
|
||||
function addLog(msg, save = true) {
|
||||
const time = new Date().toLocaleTimeString();
|
||||
const item = document.createElement('div');
|
||||
item.className = 'log-item';
|
||||
item.innerHTML = `<span class="log-time">[${time}]</span><span class="log-msg">${msg}</span>`;
|
||||
logList.insertBefore(item, logList.firstChild);
|
||||
|
||||
// 限制 DOM 节点数量,避免页面卡顿(虽然存储 5000 条,但显示建议限制在 200 条)
|
||||
if (logList.childNodes.length > 200) {
|
||||
logList.removeChild(logList.lastChild);
|
||||
}
|
||||
|
||||
// 调用安卓接口持久化存储
|
||||
if (save && window.android && window.android.saveMessage) {
|
||||
window.android.saveMessage(`${time}: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
function updateWSStatus(connected) {
|
||||
const tag = document.getElementById('ws-status-tag');
|
||||
if (connected) {
|
||||
tag.innerText = "已连接";
|
||||
tag.className = "ws-status ws-connected";
|
||||
} else {
|
||||
tag.innerText = "已断开";
|
||||
tag.className = "ws-status ws-disconnected";
|
||||
}
|
||||
}
|
||||
|
||||
function connectWS() {
|
||||
if (ws) ws.close();
|
||||
|
||||
addLog("正在尝试连接: " + clientId, false);
|
||||
ws = new WebSocket(wsUrl + clientId);
|
||||
|
||||
ws.onopen = () => {
|
||||
updateWSStatus(true);
|
||||
addLog("连接成功", false);
|
||||
startHeartbeat();
|
||||
clearTimeout(reconnectTimer);
|
||||
};
|
||||
|
||||
ws.onmessage = (evt) => {
|
||||
addLog("收到消息: " + evt.data);
|
||||
// 如果收到打印指令,可以自动触发打印
|
||||
if (evt.data.includes("print")) {
|
||||
callRawPrint();
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
updateWSStatus(false);
|
||||
addLog("连接关闭", false);
|
||||
stopHeartbeat();
|
||||
// 5秒后自动重连
|
||||
reconnectTimer = setTimeout(connectWS, 5000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
addLog("连接发生错误", false);
|
||||
};
|
||||
}
|
||||
|
||||
function toggleWS() {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
ws.close();
|
||||
} else {
|
||||
connectWS();
|
||||
}
|
||||
}
|
||||
|
||||
function startHeartbeat() {
|
||||
stopHeartbeat();
|
||||
heartbeatTimer = setInterval(() => {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send("ping");
|
||||
}
|
||||
}, 30000); // 30秒心跳
|
||||
}
|
||||
|
||||
function stopHeartbeat() {
|
||||
clearInterval(heartbeatTimer);
|
||||
}
|
||||
|
||||
function clearHistory() {
|
||||
if (confirm("确定要清空安卓端存储的所有消息吗?")) {
|
||||
if (window.android && window.android.clearMessages) {
|
||||
window.android.clearMessages();
|
||||
}
|
||||
logList.innerHTML = '<div class="log-item">记录已清空</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function manualAddRecord() {
|
||||
const text = prompt("请输入要保存的消息内容:", "手动测试记录");
|
||||
if (text) {
|
||||
addLog("用户新增: " + text);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化加载历史记录
|
||||
function loadHistory() {
|
||||
if (window.android && window.android.getMessages) {
|
||||
const history = window.android.getMessages();
|
||||
logList.innerHTML = ""; // 先清空当前显示
|
||||
if (history) {
|
||||
const msgs = history.split("|---|");
|
||||
addLog(`系统: 已从安卓端同步 ${msgs.length} 条记录`, false);
|
||||
msgs.forEach((msg, index) => {
|
||||
if (!msg || index > 500) return; // 界面显示限制前500条,防止卡死
|
||||
const item = document.createElement('div');
|
||||
item.className = 'log-item';
|
||||
const parts = msg.split(": ");
|
||||
const time = parts[0];
|
||||
const content = parts.slice(1).join(": ");
|
||||
item.innerHTML = `<span class="log-time">[${time}]</span><span class="log-msg">${content}</span>`;
|
||||
logList.appendChild(item);
|
||||
});
|
||||
} else {
|
||||
addLog("系统: 终端暂无保存的记录", false);
|
||||
}
|
||||
} else {
|
||||
alert("未检测到安卓接口,无法同步");
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(loadHistory, 500);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -89,4 +89,35 @@ class AndroidInterface(private val activity: MainActivity) {
|
|||
"1.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JS 调用:保存消息记录
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun saveMessage(message: String) {
|
||||
val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE)
|
||||
val currentMsgs = prefs.getString("history", "") ?: ""
|
||||
val updatedMsgs = if (currentMsgs.isEmpty()) message else "$message|---|$currentMsgs"
|
||||
// 限制保存最近5000条
|
||||
val list = updatedMsgs.split("|---|").take(5000)
|
||||
prefs.edit().putString("history", list.joinToString("|---|")).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* JS 调用:获取消息记录
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun getMessages(): String {
|
||||
val prefs = activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE)
|
||||
return prefs.getString("history", "") ?: ""
|
||||
}
|
||||
|
||||
/**
|
||||
* JS 调用:清空消息记录
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun clearMessages() {
|
||||
activity.getSharedPreferences("msg_records", Context.MODE_PRIVATE).edit().clear().apply()
|
||||
Toast.makeText(activity, "消息记录已清空", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -68,6 +68,9 @@ class MainActivity : AppCompatActivity() {
|
|||
}
|
||||
|
||||
fun showExitDialog() {
|
||||
// 调用 JS 函数
|
||||
mAgentWeb?.jsAccessEntrace?.quickCallJs("addExitText")
|
||||
|
||||
androidx.appcompat.app.AlertDialog.Builder(this)
|
||||
.setTitle("提示")
|
||||
.setMessage("确定要退出应用吗?")
|
||||
|
|
|
|||
Loading…
Reference in New Issue