Skip to content

Commit

Permalink
优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyJiangWJ committed Sep 30, 2020
1 parent 4a5095d commit f2c9def
Show file tree
Hide file tree
Showing 10 changed files with 135 additions and 71 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
- 封装了支持多脚本锁的 `LockableStorage`,阻塞写入并返回写入成功与否,达到锁互斥的目的
- 封装了基于文本、ID控件正则查找工具 `WidgetUtils`,支持控件等待,批量获取匹配控件等等
- 日志工具 `LogUtils`,可以保存日志到文件,支持日志级别 error\warn\info\log\debug,不同级别日志控制台中不同颜色显示,且开启日志文件后写入到不同的文件中。
- 日志支持同步写入文件和异步写入文件两种方式,写这个仅仅是想要实现双缓冲异步写入这么个东西
- 异步方式的日志文件不是立马刷新到文件的,在脚本完全执行完毕之后才会完全写入
- 因此如果需要性能则选择启用异步方式,否则使用同步就行。
- 支持 `github release api` 的脚本手动更新功能
- 支持自动判断Root和无障碍的自动化执行操作 `Automator`
- 封装了一个文本悬浮窗工具 `FloatyUtil`
Expand Down
3 changes: 2 additions & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ let default_config = {
// 是否是AutoJS Pro 需要屏蔽部分功能,暂时无法实现:生命周期监听等 包括通话监听
is_pro: is_pro,
auto_set_bang_offset: true,
bang_offset: 0
bang_offset: 0,
thread_name_prefix: 'autoscript_'
}
// 不同项目需要设置不同的storageName,不然会导致配置信息混乱
let CONFIG_STORAGE_NAME = 'autoscript_version'
Expand Down
21 changes: 12 additions & 9 deletions lib/ResourceMonitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
* @Author: TonyJiangWJ
* @Date: 2020-05-11 18:28:23
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-08-24 18:00:22
* @Last Modified time: 2020-09-25 21:57:26
* @Description: 图片资源监听并自动回收
*/
let { config } = require('../config.js')(runtime, this)

let sRequire = require('./SingletonRequirer.js')(runtime, this)
let { debugInfo, debugForDev, infoLog, errorInfo } = sRequire('LogUtils')
let commonFunctions = sRequire('CommonFunction')
function isNullOrUndefined(val) {
function isNullOrUndefined (val) {
return val === null || typeof val === 'undefined'
}

Expand All @@ -26,17 +26,20 @@ module.exports = function (__runtime__, scope) {
this.init()
}

ResourceMonitor.prototype.releaseAll = function () {
ResourceMonitor.prototype.releaseAll = function (undelegated) {
if (this.images !== null) {
debugInfo('释放图片,总数:' + (this.images.length + this.longHoldImages.length))
try {
this.writeLock.lock()
this.recycleImages(this.images.splice(0), true)
this.recycleImages(this.longHoldImages.splice(0), true)
this.images = null
scope.images = _o_images
scope.__asGlobal__(_o_images, ['captureScreen'])
_o_images = null
if (undelegated) {
debugInfo('解除图像资源代理')
this.images = null
scope.images = _o_images
scope.__asGlobal__(_o_images, ['captureScreen'])
_o_images = null
}
} finally {
this.writeLock.unlock()
}
Expand Down Expand Up @@ -105,7 +108,7 @@ module.exports = function (__runtime__, scope) {
imageInfo.img.recycle()
} catch (e) {
// console.warn('释放图片异常' + e)
count ++
count++
}
})
debugInfo(desc + ',耗时' + (new Date().getTime() - start) + (count > 0 ? ', 其中有:' + count + '自动释放了' : ''))
Expand Down Expand Up @@ -316,7 +319,7 @@ module.exports = function (__runtime__, scope) {

commonFunctions.registerOnEngineRemoved(function () {
infoLog('脚本执行结束, 释放图片资源')
resourceMonitor.releaseAll()
resourceMonitor.releaseAll(true)
}, 'resourceMonitor')

scope.resourceMonitor = resourceMonitor
Expand Down
26 changes: 16 additions & 10 deletions lib/Unlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @Author: TonyJiangWJ
* @Date: 2019-11-05 09:12:00
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-09-22 21:22:03
* @Last Modified time: 2020-09-30 21:41:00
* @Description:
*/
let { config: _config, storageName: _storageName } = require('../config.js')(runtime, this)
Expand All @@ -14,9 +14,9 @@ let _runningQueueDispatcher = singletonRequire('RunningQueueDispatcher')
let ExternalUnlockDevice = files.exists(FileUtils.getCurrentWorkPath() + '/extends/ExternalUnlockDevice.js') ? require('../extends/ExternalUnlockDevice.js') : null

if (ExternalUnlockDevice) {
log('使用自定义解锁模块')
logInfo('使用自定义解锁模块')
} else {
log('使用内置解锁模块')
logInfo('使用内置解锁模块')
}

let XIAOMI_MIX2S = function (obj) {
Expand Down Expand Up @@ -66,6 +66,10 @@ let XIAOMI_MIX2S = function (obj) {

// 判断解锁方式并解锁
this.unlock = function (password) {
if (typeof password === 'undefined' || password === null || password.length === 0) {
errorInfo('密码为空:' + JSON.stringify(password))
throw new Error('密码为空!')
}
if (id('com.android.systemui:id/lockPatternView').exists()) {
return this.unlock_pattern(password)
} else if (id('com.android.systemui:id/passwordEntry').exists()) {
Expand All @@ -88,7 +92,6 @@ function Unlocker () {
const _km = context.getSystemService(context.KEYGUARD_SERVICE)

this.relock = false
this.notRelock = false
this.reTry = 0

// 设备是否锁屏
Expand All @@ -111,6 +114,7 @@ function Unlocker () {
device.setBrightnessMode(1)
}
_runningQueueDispatcher.removeRunningTask()
this.saveNeedRelock(true)
engines.myEngine().forceStop()
} else {
let sleepMs = 5000 * this.reTry
Expand Down Expand Up @@ -184,6 +188,7 @@ function Unlocker () {
}
}
this.relock = true
_config.notNeedRelock = false
logInfo('需要重新锁定屏幕')
// 首先点亮屏幕
this.wakeup()
Expand All @@ -194,6 +199,7 @@ function Unlocker () {
// 如果解锁失败
this.failed()
} else {
this.saveNeedRelock()
if (_config.dismiss_dialog_if_locked) {
// 锁屏状态下启动不再弹框倒计时
_commonFunctions.getAndUpdateDismissReason('screen_locked')
Expand All @@ -202,11 +208,13 @@ function Unlocker () {
}

this.saveNeedRelock = function (notRelock) {
if (notRelock) {
this.notRelock = true
this.relock = this.relock || this.getRelockInfo()
if (notRelock || _config.notNeedRelock) {
this.relock = false
}
let storage = storages.create(_storageName)
storage.put('needRelock', JSON.stringify({needRelock: !this.notRelock && this.relock, timeout: new Date().getTime() + 30000 }))
debugInfo('保存是否需要重新锁屏:' + this.relock)
storage.put('needRelock', JSON.stringify({needRelock: this.relock && this.relock, timeout: new Date().getTime() + 30000 }))
}

this.getRelockInfo = function () {
Expand All @@ -230,9 +238,7 @@ module.exports = {
},
needRelock: function () {
logInfo('是否需要重新锁定屏幕:' + _unlocker.relock)
let tmp = _unlocker.relock
_unlocker.relock = false
return tmp
return _unlocker.relock
},
saveNeedRelock: function (notRelock) {
_unlocker.saveNeedRelock(notRelock)
Expand Down
3 changes: 2 additions & 1 deletion lib/prototype/Automator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @Author: TonyJiangWJ
* @Date: 2020-04-25 20:37:31
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-05-09 07:46:51
* @Last Modified time: 2020-09-25 19:43:25
* @Description:
*/
let { config: _config } = require('../../config.js')(runtime, this)
Expand Down Expand Up @@ -37,6 +37,7 @@ module.exports = {
return _automator.back()
},
lockScreen: function () {
_config.notNeedRelock = true
return _automator.lockScreen()
},
scrollDown: function (speed) {
Expand Down
93 changes: 71 additions & 22 deletions lib/prototype/CommonFunction.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @Author: TonyJiangWJ
* @Date: 2020-04-25 20:16:09
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-09-24 22:10:35
* @Last Modified time: 2020-09-27 14:14:08
* @Description: 通用工具
*/
importClass(android.content.Context)
Expand Down Expand Up @@ -40,49 +40,93 @@ let ENGINE_ID = engines.myEngine().id
lifecycleDeamonThreadPool = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(10), new ThreadFactory({
newThread: function (runnable) {
let thread = Executors.defaultThreadFactory().newThread(runnable)
thread.setName(ENGINE_ID + '-lifecycle-deamon-' + thread.getName())
thread.setName(_config.thread_name_prefix + ENGINE_ID + '-lifecycle-deamon-' + thread.getName())
return thread
}
}))
lifecycleDeamonThreadPool.execute(function () {
let count = 0
while (_config.isRunning) {
// 每五秒检测一次isRunning
sleep(5000)
if (count++ % 5) {
// 每25秒执行一次,其实在LogUtils中已经有了校验,这里增加判断,冗余一下
let currentEngine = engines.all().filter(engine => engine.id === ENGINE_ID)
_config.isRunning = currentEngine && currentEngine.length > 0
}
}
console.verbose('脚本已经中止执行,执行生命周期回调')
// 脚本已经结束,执行callbacks
if (lifecycleCallbacks && lifecycleCallbacks.length > 0) {
lifecycleCallbacks.forEach(callback => {
callback()
})
// 每0.5秒检测一次isRunning, 5秒太慢了
sleep(500)
let currentEngine = engines.all().filter(engine => engine.id === ENGINE_ID)
_config.isRunning = currentEngine && currentEngine.length > 0
}
_logUtils.debugInfo('脚本已经中止执行,执行生命周期回调')
try {
// 脚本已经结束,执行callbacks
if (lifecycleCallbacks && lifecycleCallbacks.length > 0) {
lifecycleCallbacks.forEach(callback => {
try {
_logUtils.debugInfo('执行生命周期回调:' + callback.desc)
callback.func()
} catch (e) {
_logUtils.errorInfo(callback.desc + ' 生命周期回调异常' + e)
}
})
}
} catch (e) {
_logUtils.errorInfo('执行生命周期回调异常' + e)
}
// 新建线程 关闭线程池
let thread = new Thread(new java.lang.Runnable({
run: function () {
try {
lifecycleDeamonThreadPool.shutdown()
let flag = lifecycleDeamonThreadPool.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)
console.verbose('lifecycleDeamon线程池关闭:' + flag)
let flag = lifecycleDeamonThreadPool.awaitTermination(5, TimeUnit.SECONDS)
_logUtils.debugInfo('lifecycleDeamon线程池关闭:' + flag)
} catch (e) {
console.error('关闭lifecycleDeamon线程池异常:' + e)
_logUtils.errorInfo('关闭lifecycleDeamon线程池异常:' + e)
} finally {
lifecycleDeamonThreadPool = null
}
}
}))
thread.setName(ENGINE_ID + "_shutdown_lifecycle_thread")
thread.setName(_config.thread_name_prefix + ENGINE_ID + "_shutdown_lifecycle_thread")
thread.start()
})


function CommonFunctions () {

/**
* 确保识别区域在图片范围内,超范围的自动压缩宽高
* @param {array} region 识别区域范围[x, y, width, height]
* @param {int} maxWidth 最大宽度
* @param {int} maxHeight 最大高度
*/
this.ensureRegionInScreen = function (region, maxWidth, maxHeight) {
maxWidth = maxWidth || _config.device_width
maxHeight = maxHeight || _config.device_height
let flag = 0
if (region[0] > maxWidth || region[0] < 0) {
_logUtils.errorInfo(['x起始点超范围:{}', region[0]])
throw new java.lang.IllegalArgumentException('x起始点超范围:' + region[0])
}
if (region[1] > maxHeight || region[1] < 0) {
_logUtils.errorInfo(['y起始点超范围:{}', region[0]])
throw new java.lang.IllegalArgumentException('y起始点超范围:' + region[1])
}
let width = region[0] + region[2]
let height = region[1] + region[3]
if (width > maxWidth) {
region[2] = maxWidth - region[0]
flag = flag | 1
}
if (height > maxHeight) {
region[3] = maxHeight - region[1]
flag = flag | 2
}
if (flag !== 0) {
_logUtils.debugInfo(['检测识别区域是否超范围:{} maxW: {} maxH: {}', JSON.stringify(region), maxWidth, maxHeight])
if (flag & 1 === 1) {
_logUtils.debugInfo(['宽度超范围 修正为:{}', region[2]])
}
if (flag & 2 === 2) {
_logUtils.debugInfo(['高度超范围 修正为:{}', region[3]])
}
}
}

/**
* 自动设置刘海的偏移量
*/
Expand Down Expand Up @@ -139,7 +183,7 @@ function CommonFunctions () {
this.registerOnEngineRemoved = function (func, desc) {
desc = desc || 'common func'
lifecycleLock.lock()
lifecycleCallbacks.push(func)
lifecycleCallbacks.push({ func: func, desc: desc })
lifecycleLock.unlock()
}

Expand Down Expand Up @@ -362,6 +406,8 @@ function CommonFunctions () {
}
this.cancelAllTimedTasks()
_runningQueueDispatcher.removeRunningTask()
// 不需要锁屏
_config.notNeedRelock = true
exit()
}
if (continueRunning) {
Expand Down Expand Up @@ -717,6 +763,9 @@ function CommonFunctions () {
action()
actionSuccess = true
} catch (e) {
if (e.javaException instanceof com.stardust.autojs.runtime.exception.ScriptInterruptedException) {
return
}
_logUtils.warnInfo('action执行异常' + e)
that.printExceptionStack(e)
} finally {
Expand Down
Loading

0 comments on commit f2c9def

Please sign in to comment.