WebSocket、定时任务与高级网络 — AutoJs6 网络能力全景
HTTP 网络请求
AutoJs6 内置 http 模块,支持完整的 HTTP/HTTPS 请求能力。v6.7 新增了 HTTP 异步方法和更多选项。
基本请求
// GET 请求
let response = http.get("https://api.example.com/data");
console.log("状态码: " + response.statusCode);
console.log("响应: " + response.body.string());
// POST 请求
let response = http.post("https://api.example.com/submit", {
body: {
name: "AutoJs6",
version: "6.7"
}
});
console.log(response.body.json());
// PUT / DELETE / HEAD(v6.7 新增)
http.put("https://api.example.com/update", { body: {...} });
http.del("https://api.example.com/delete");
http.head("https://api.example.com/headers");
请求选项
let response = http.get("https://api.example.com/data", {
// 请求头
headers: {
"User-Agent": "AutoJs6/6.7",
"Authorization": "Bearer token123"
},
// 超时
timeout: 10000,
// 跟随重定向
followRedirects: true,
// v6.7 新增:缓存控制
cacheBody: true,
bodyCacheThresholdBytes: 1024,
// v6.7 新增:忽略证书异常
insecure: false, // true = 忽略 SSL 证书错误
// v6.7 新增:自定义 OkHttpClient
client: null // 可传入自定义 OkHttpClient.Builder
});
HTTP 异步请求(v6.7 新增)
// 异步 GET
http.getAsync("https://api.example.com/data").then(response => {
console.log("响应: " + response.body.string());
}).catch(err => {
console.error("请求失败: " + err.message);
});
// 异步 POST
http.postAsync("https://api.example.com/submit", {
body: { name: "test" }
}).then(response => {
console.log(response.statusCode);
});
// 通用异步请求
http.requestAsync({
url: "https://api.example.com/data",
method: "GET",
headers: {...}
});
响应 body 方法(v6.7 新增)
let response = http.get("https://...");
let body = response.body;
// 读取内容
body.string(); // 字符串
body.json(); // JSON 对象
body.bytes(); // 字节数组
// v6.7 新增的流式处理
body.stream(); // 流式读取
body.saveToFile("/sdcard/download.bin"); // 直接保存到文件
body.close(); // 手动关闭
WebSocket 实时通信
AutoJs6 支持 WebSocketType 模块,实现浏览器式的实时通信能力:
// 连接 WebSocket 服务器
let ws = new WebSocketType("wss://example.com/ws");
// 连接成功
ws.on("open", () => {
console.log("WebSocket 已连接");
ws.send("Hello Server!");
});
// 收到消息
ws.on("message", (message) => {
console.log("收到: " + message);
// 自动回复
ws.send("收到消息: " + message);
});
// 连接关闭
ws.on("close", (code, reason) => {
console.log("连接关闭: " + code + " " + reason);
});
// 错误
ws.on("error", (err) => {
console.error("错误: " + err.message);
});
重连逻辑
let ws;
let reconnectDelay = 3000;
function connect() {
ws = new WebSocketType("wss://example.com/ws");
ws.on("open", () => {
console.log("已连接");
reconnectDelay = 3000; // 重置延迟
});
ws.on("close", () => {
console.log("连接断开," + reconnectDelay + "ms 后重连...");
setTimeout(() => {
connect();
reconnectDelay = Math.min(reconnectDelay * 2, 30000); // 指数退避,最大 30s
}, reconnectDelay);
});
ws.on("error", () => ws.close());
}
connect();
定时任务调度
引擎选择(v6.7 新增)
Android 有三种定时任务调度机制,各有特点:
| 引擎 | 精度 | 后台存活 | 适用场景 |
|---|---|---|---|
| AlarmManager | ⭐⭐ | ✅ 高 | 需要精确触发的定时任务 |
| WorkManager | ⭐⭐⭐ | ✅⭐⭐ 中 | 弹性时间、可延迟的任务 |
| JobScheduler | ⭐⭐⭐ | ✅⭐⭐ 中 | Android 5+ 原生调度 |
AutoJs6 设置 → 无障碍 → 定时任务调度引擎,可切换默认引擎。
setTimeout / setInterval
// 单次定时
setTimeout(() => {
console.log("5 秒后执行");
}, 5000);
// 循环定时
let interval = setInterval(() => {
console.log("每秒一次");
}, 1000);
// 停止循环
clearInterval(interval);
schedule 模块
// 更精确的定时调度
// 具体 API 以文档为准
// 每天特定时间执行
// schedule.daily("08:00", () => { ... });
// 每隔 N 分钟执行
// schedule.interval(30, () => { ... });
后台定时注意事项
Android 系统对后台进程管控严格,定时任务可能被系统延迟或取消。建议:
- 把 AutoJs6 加入电池优化白名单
- 使用
AlarmManager引擎(更精确) - 在任务执行前检查 AutoJs6 是否被系统重启过
// 脚本开头检查是否是首次启动
let isFirstRun = storage.get("firstRun", true);
if (isFirstRun) {
console.log("首次运行,初始化...");
storage.put("firstRun", false);
}
实战:WebSocket + 定时任务混合
/**
* 实时监听指令 + 定时上报状态
*/
let status = {
battery: 0,
network: "unknown",
running: true
};
// WebSocket 连接接收远程指令
let ws = new WebSocketType("wss://remote-control.example.com/device");
ws.on("open", () => {
console.log("已连接到远程控制台");
// 上报设备信息
ws.send(JSON.stringify({
type: "register",
deviceId: device.getSharedDeviceId()
}));
});
ws.on("message", (msg) => {
let cmd = JSON.parse(msg);
if (cmd.type === "run") {
// 执行远程下发的脚本
eval(cmd.script); // 注意安全风险
ws.send(JSON.stringify({ type: "result", success: true }));
}
if (cmd.type === "stop") {
status.running = false;
exit();
}
});
// 定时上报状态
setInterval(() => {
status.battery = device.battery;
// 其他状态采集...
if (ws.state === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: "heartbeat",
data: status
}));
}
}, 30000); // 每 30 秒上报
网络安全注意事项
// 不推荐:忽略 SSL 证书验证(v6.7 的 insecure 选项)
// http.get("https://...", { insecure: true });
// 这会降低安全性,只在测试 / 内网自签名场景使用
// 推荐:正确配置 CA 证书
// 或由系统证书存储自动处理
// 注意 URL 编码
let keyword = "AutoJs6 高级功能";
let url = "https://api.example.com/search?q=" + encodeURIComponent(keyword);