图片回收

// 先判断是否已经回收

if(bitmap != null && !bitmap.isRecycled()){  

        // 回收并且置为null

        bitmap.recycle();  

        bitmap = null;  

}  

System.gc();

非常好的问题! 在 Auto.js 中使用 `captureScreen()` 和 `images.read()` 会占用 **内存中的图像缓冲区(Bitmap)**,如果不及时回收,长时间运行会导致: > ❌ 内存泄漏 > ❌ 脚本变慢甚至崩溃 > ❌ `OutOfMemoryError` 因此,**必须为图片添加回收机制**。 --- ## ✅ 正确做法:使用 `recycle()` 回收图片资源 Auto.js 的 `Image` 对象(来自 `captureScreen()` 或 `images.read()`)提供了 `.recycle()` 方法来释放底层 Bitmap 资源。 --- ### ✅ 修复后的完整代码(含图片回收) ```javascript // 检查筛选控件是否存在 if (id("filter_iv").className("android.widget.TextView").exists()) { // Step 1: 截图 var cap = captureScreen(); if (!cap) { toast("❌ 截图失败"); exit(); } // Step 2: 加载模板图 var templatePath = "/sdcard/脚本/小图/筛选.png"; var tem = images.read(templatePath); if (!tem) { toast("❌ 模板图片加载失败: " + templatePath); cap.recycle(); // ⛔️ 别忘了回收截图! exit(); } // Step 3: 图像比对 var p = images.findImage(cap, tem, { region: [957, 293, 1199 - 957, 360 - 293], // x, y, width, height threshold: 0.9 }); if (p) { log("✅ 找到筛选图标,坐标:", p); log("正常运行"); // ✅ 比对完成后立即回收两张图 cap.recycle(); tem.recycle(); } else { log("⚠️ 未找到筛选图标,触发警报!"); // 回收资源 cap.recycle(); tem.recycle(); // 设置音量 device.setMusicVolume(7); // 播放提醒音乐 var musicPath = "/sdcard/Music/My love 请别让爱凋落.mp3"; if (files.exists(musicPath)) { media.playMusic(musicPath); sleep(100); var duration = media.getMusicDuration(); if (duration > 0) { sleep(duration + 500); } else { sleep(5000); // 安全兜底 } } else { toast("🎵 音乐文件不存在"); device.vibrate(2000); sleep(2000); } // 停止脚本 engines.myEngine().forceStop(); } } else { log("🔍 尚未发现筛选控件,继续运行..."); } ``` --- ## ✅ 图片回收核心原则 | 原则 | 说明 | |------|------| | ✅ **每张通过 `captureScreen()` 或 `images.read()` 得到的图片都必须 `recycle()`** | 否则内存泄露 | | ✅ **使用完就立刻回收** | 不要等到脚本结束 | | ✅ **即使出错也要回收** | 特别是在 `try-catch` 或条件分支中 | --- ## ✅ 推荐封装:安全图像匹配函数(自动回收) ```js /** * 安全图像查找(自动回收资源) * @param {string} imagePath 模板图路径 * @param {array} region 查找区域 [x, y, w, h] * @param {number} threshold 相似度阈值 * @returns {Point|null} 匹配点或 null */ function findImageSafely(imagePath, region, threshold) { var cap = captureScreen(); var tem = images.read(imagePath); if (!cap || !tem) { if (cap) cap.recycle(); if (tem) tem.recycle(); return null; } var p = images.findImage(cap, tem, { region: region, threshold: threshold || 0.9 }); // ✅ 必须回收! cap.recycle(); tem.recycle(); return p; } // 使用示例: var point = findImageSafely("/sdcard/脚本/小图/筛选.png", [957, 293, 242, 67]); if (point) { log("✅ 找到图标"); } else { log("❌ 未找到"); } ``` --- ## ✅ 补充建议 | 建议 | 说明 | |------|------| | 🔋 长时间运行脚本建议每轮循环后 `sleep(100)` 并手动 `gc()` | 减少内存压力 | | 🧼 可主动调用 `java.lang.System.gc()` 提示垃圾回收 | 非强制,但有帮助 | | 📊 测试时打开“显示内存信息”选项 | 观察内存是否持续增长 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值