Skip to content

Commit

Permalink
优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyJiangWJ committed Aug 24, 2020
1 parent 65e9d4f commit 02d3386
Show file tree
Hide file tree
Showing 9 changed files with 282 additions and 133 deletions.
22 changes: 17 additions & 5 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@

let currentEngine = engines.myEngine().getSource() + ''
let isRunningMode = currentEngine.endsWith('/config.js') && typeof module === 'undefined'


let is_pro = Object.prototype.toString.call(com.stardust.autojs.core.timing.TimedTask.Companion).match(/Java(Class|Object)/)
let default_config = {
password: '',
is_alipay_locked: false,
alipay_lock_password: '',
timeout_unlock: 1000,
timeout_findOne: 1000,
timeout_existing: 8000,
// 异步等待截图,当截图超时后重新获取截图 默认开启
async_waiting_capture: true,
capture_waiting_time: 500,
show_debug_log: true,
show_engine_id: false,
Expand All @@ -44,7 +45,9 @@ let default_config = {
// 延迟启动时延 5秒 悬浮窗中进行的倒计时时间
delayStartTime: 5,
device_width: device.width,
device_height: device.height
device_height: device.height,
// 是否是AutoJS Pro 需要屏蔽部分功能,暂时无法实现:生命周期监听等 包括通话监听
is_pro: is_pro
}
// 不同项目需要设置不同的storageName,不然会导致配置信息混乱
let CONFIG_STORAGE_NAME = 'autoscript_version'
Expand Down Expand Up @@ -173,7 +176,8 @@ if (!isRunningMode) {
ui.timeoutFindOneInpt.text(config.timeout_findOne + '')
ui.timeoutExistingInpt.text(config.timeout_existing + '')
ui.captureWaitingTimeInpt.text(config.capture_waiting_time + '')

ui.asyncWaitingCaptureChkBox.setChecked(config.async_waiting_capture)
ui.asyncWaitingCaptureContainer.setVisibility(config.async_waiting_capture ? View.VISIBLE : View.GONE)
// 进阶配置
ui.singleScriptChkBox.setChecked(config.single_script)
setScrollDownUiVal()
Expand Down Expand Up @@ -304,7 +308,9 @@ if (!isRunningMode) {
<text text="校验控件是否存在超时(ms):" />
<input id="timeoutExistingInpt" inputType="number" layout_weight="60" />
</horizontal>
<horizontal gravity="center">
<text text="偶尔通过captureScreen获取截图需要等待很久,或者一直阻塞无法进行下一步操作,建议开启异步等待,然后设置截图等待时间(默认500ms,需自行调试找到合适自己设备的数值)。失败多次后脚本会自动重启,重新获取截图权限" textSize="10dp" />
<checkbox id="asyncWaitingCaptureChkBox" text="是否异步等待截图" />
<horizontal gravity="center" id="asyncWaitingCaptureContainer">
<text text="获取截图等待时间(ms):" />
<input id="captureWaitingTimeInpt" inputType="number" layout_weight="60" />
</horizontal>
Expand Down Expand Up @@ -479,6 +485,12 @@ if (!isRunningMode) {
config.dismiss_dialog_if_locked = ui.dismissDialogIfLockedChkBox.isChecked()
})


ui.asyncWaitingCaptureChkBox.on('click', () => {
config.async_waiting_capture = ui.asyncWaitingCaptureChkBox.isChecked()
ui.asyncWaitingCaptureContainer.setVisibility(config.async_waiting_capture ? View.VISIBLE : View.GONE)
})

ui.autoLockChkBox.on('click', () => {
let checked = ui.autoLockChkBox.isChecked()
config.auto_lock = checked
Expand Down
42 changes: 42 additions & 0 deletions lib/AutoJSRemoveDexResolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* @Author: TonyJiangWJ
* @Date: 2020-08-04 17:30:20
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-08-05 13:52:17
* @Description:
*/

/**
* 免费版的runtime.loadDex loadJar有问题,加载前需要将mDexClassLoaders清空
*/
const _resolver = () => {
console.verbose('run resolver')
try {
let packageName = context.getPackageName()
console.verbose('packageName: ' + packageName)
if (packageName === 'org.autojs.autojs') {
importClass(java.lang.Class)
let target = org.mozilla.javascript.ContextFactory.getGlobal().getApplicationClassLoader()
let clz = target.getClass()
console.verbose("clz:" + clz.toString())
let field = clz.getDeclaredField("mDexClassLoaders")
field.setAccessible(true)
let fieldValue = field.get(target)
let fieldClass = fieldValue.getClass()

if (fieldClass + '' === 'class java.util.ArrayList') {
fieldValue.clear()
console.verbose("success")
} else {
console.verbose("fieldValue is not list")
}
}
} catch (e) {
let errorInfo = e + ''
console.error('发生异常' + errorInfo)
toastLog('请强制关闭AutoJS并重新启动')
exit()
}
}

module.exports = _resolver
62 changes: 32 additions & 30 deletions lib/ResourceMonitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@
* @Author: TonyJiangWJ
* @Date: 2020-05-11 18:28:23
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-06-02 09:39:20
* @Last Modified time: 2020-08-24 18:00:22
* @Description: 图片资源监听并自动回收
*/
let { config } = require('../config.js')(runtime, this)

if (!config.is_pro) {
importClass(com.stardust.autojs.ScriptEngineService)
importClass(com.stardust.autojs.engine.ScriptEngineManager)
}
let sRequire = require('./SingletonRequirer.js')(runtime, this)
let { debugInfo, debugForDev, infoLog, errorInfo } = sRequire('LogUtils')
let commonFunctions = sRequire('CommonFunction')
function isNullOrUndefined(val) {
return val === null || typeof val === 'undefined'
}

module.exports = function (__runtime__, scope) {
if (typeof scope.resourceMonitor === 'undefined' || scope.resourceMonitor === null) {
let _o_images = scope.images
let _o_images = require('__images__.js')(__runtime__, scope)
debugInfo(['Is _origin_images null? {}.', isNullOrUndefined(_o_images)])
function ResourceMonitor () {
this.images = []
// 需要长时间持有的图片,不会自动动态释放
Expand Down Expand Up @@ -64,7 +65,9 @@ module.exports = function (__runtime__, scope) {
ResourceMonitor.prototype.addImageToList = function (img) {

try {
debugForDev('准备获取图片资源锁')
this.writeLock.lock()
debugForDev('获取图片资源锁成功')
if (this.images === null) {
// this is only happen when engine stoped, just recycle img
debugInfo('检测到脚本已停止,直接回收图片')
Expand Down Expand Up @@ -124,14 +127,17 @@ module.exports = function (__runtime__, scope) {

let that = this

const M_Images = function () {
let M_Images = function () {
_o_images.constructor.call(this)
}
M_Images.prototype = Object.create(_o_images.prototype)
M_Images.prototype.constructor = _o_images

M_Images.prototype.captureScreen = function () {
let start = new Date().getTime()
debugForDev('准备获取截图')
let img = _o_images.captureScreen()
debugForDev(['获取截图完成,耗时{}ms', (new Date().getTime() - start)])
that.addImageToList(img)
return img
}
Expand Down Expand Up @@ -266,6 +272,18 @@ module.exports = function (__runtime__, scope) {
return nImg
}

M_Images.prototype.isDelegated = function () {
return true
}

M_Images.prototype.isValidImg = function (img) {
try {
img.ensureNotRecycled()
return true
} catch (e) {
return false
}
}
let mImages = new M_Images()

let newImages = {}
Expand All @@ -286,37 +304,21 @@ module.exports = function (__runtime__, scope) {
newImages[func_name] = mImages[func_name]
}
}

debugInfo('图片资源代理创建完毕,准备替换scope中的images')
scope.images = newImages

scope.__asGlobal__(mImages, ['captureScreen'])
debugInfo('图片资源代理替换images完毕')
}

let resourceMonitor = new ResourceMonitor()

if (!config.is_pro) {
// 监听运行周期,脚本结束后释放图片资源
let engineService = ScriptEngineService.getInstance()

let myEngineId = engines.myEngine().id
engineService.registerEngineLifecycleCallback(
new ScriptEngineManager.EngineLifecycleCallback({
onEngineCreate: function (engine) {
},
onEngineRemove: function (engine) {
if (engine.id === myEngineId) {
infoLog('脚本执行结束, 释放图片资源')
resourceMonitor.releaseAll()
}
}
})
)
} else {
errorInfo('Pro版无法监听生命周期,请尽量使用免费版')
}
commonFunctions.registerOnEngineRemoved(function () {
infoLog('脚本执行结束, 释放图片资源')
resourceMonitor.releaseAll()
}, 'resourceMonitor')

scope.resourceMonitor = resourceMonitor
}

return scope.resourceMonitor
}
}
22 changes: 16 additions & 6 deletions lib/Unlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ let singletonRequire = require('./SingletonRequirer.js')(runtime, this)
let automator = singletonRequire('Automator')
let FileUtils = singletonRequire('FileUtils')
let _commonFunctions = singletonRequire('CommonFunction')
let _runningQueueDispatcher = singletonRequire('RunningQueueDispatcher')
let ExternalUnlockDevice = files.exists(FileUtils.getCurrentWorkPath() + '/extends/ExternalUnlockDevice.js') ? require('../extends/ExternalUnlockDevice.js') : null

if (ExternalUnlockDevice) {
Expand Down Expand Up @@ -69,7 +70,7 @@ let XIAOMI_MIX2S = function (obj) {
return this.unlock_pattern(password)
} else if (id('com.android.systemui:id/passwordEntry').exists()) {
return this.unlock_password(password)
} else if (idMatches('com.android.systemui:id/(fixed)?pinEntry').exists()) {
} else if (idMatches('com.android.systemui:id/(fixedP|p)inEntry').exists()) {
return this.unlock_pin(password)
} else {
logInfo(
Expand Down Expand Up @@ -108,6 +109,7 @@ function Unlocker () {
if (_config.auto_set_brightness) {
device.setBrightnessMode(1)
}
_runningQueueDispatcher.removeRunningTask()
engines.myEngine().forceStop()
} else {
let sleepMs = 5000 * this.reTry
Expand Down Expand Up @@ -141,11 +143,8 @@ function Unlocker () {

// 划开图层
this.swipe_layer = function () {
// let x = _WIDTH / 2
// let y = _HEIGHT / 6
// gesture(320, [x, 5 * y], [x, 1 * y])
// 暂时写死 否则兼容性较差
gesture(320, [500, parseInt(_config.device_height * 0.8)], [500, parseInt(_config.device_height * 0.3)])
let x = parseInt(_config.device_width * 0.2)
gesture(320, [x, parseInt(_config.device_height * 0.8)], [x, parseInt(_config.device_height * 0.3)])
sleep(_config.timeout_unlock)
}

Expand All @@ -162,6 +161,17 @@ function Unlocker () {
}
return true
}
// 校验设备姿态 是否在裤兜内
if (_config.check_device_posture) {
let sensorInfo = _commonFunctions.getDistanceAndGravity(1000)
if (sensorInfo.z < (_config.posture_threshod_z || 6)
&& (!_config.check_distance || sensorInfo.distance < 4)) {
_commonFunctions.setUpAutoStart(5)
warnInfo('当前设备可能在裤兜内,5分钟后尝试')
_runningQueueDispatcher.removeRunningTask()
engines.myEngine().forceStop()
}
}
this.relock = true
logInfo('需要重新锁定屏幕')
if (_config.auto_set_brightness) {
Expand Down
21 changes: 0 additions & 21 deletions lib/prototype/Automator.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,27 +140,6 @@ function CommonAutomation () {
return hasButton
}

this.enterFriendList = function (tryCount) {
tryCount = tryCount || 1
if (descEndsWith(_config.enter_friend_list_ui_content).exists()) {
descEndsWith(_config.enter_friend_list_ui_content)
.findOne(_config.timeout_findOne)
.click()
} else if (textEndsWith(_config.enter_friend_list_ui_content).exists()) {
textEndsWith(_config.enter_friend_list_ui_content)
.findOne(_config.timeout_findOne)
.click()
} else {
if (tryCount > 3) {
return
}
_logUtils.warnInfo(['未找到 查看更多好友 等待一秒钟后重试, 尝试次数:{}', tryCount])
// 未找到查看更多好友,等待1秒钟后重试
sleep(1000)
this.enterFriendList(++tryCount)
}
sleep(200)
}
}
function Automation_root () {
CommonAutomation.call(this)
Expand Down
35 changes: 10 additions & 25 deletions lib/prototype/CallStateListener.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
* @Author: TonyJiangWJ
* @Date: 2020-05-11 16:54:44
* @Last Modified by: TonyJiangWJ
* @Last Modified time: 2020-05-25 19:31:43
* @Last Modified time: 2020-08-24 18:03:46
* @Description: 监听通话状态,通话时自动延迟五分钟
*/
importClass(android.content.Context)
importClass(android.content.BroadcastReceiver)
importClass(android.content.IntentFilter)
importClass(com.stardust.autojs.ScriptEngineService)
importClass(com.stardust.autojs.engine.ScriptEngineManager)
let { config } = require('../../config.js')(runtime, this)
let sRequire = require('../SingletonRequirer.js')(runtime, this)
let commonFunctions = sRequire('CommonFunction')
Expand All @@ -20,10 +18,7 @@ function CallStateListener () {
let telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE)

this.isReceiverRegistered = false
// 监听运行周期,脚本结束后释放图片资源
let engineService = ScriptEngineService.getInstance()

let myEngineId = engines.myEngine().id
let that = this

const onReceiveCallStateChanged = function (context, intent) {
Expand Down Expand Up @@ -59,26 +54,16 @@ function CallStateListener () {


logUtils.debugInfo('添加运行状态监听器,结束时释放通话状态监听')
engineService.registerEngineLifecycleCallback(
new ScriptEngineManager.EngineLifecycleCallback({
onEngineCreate: function (engine) {
},
onEngineRemove: function (engine) {
if (engine.id === myEngineId) {
logUtils.infoLog('脚本执行结束, 移除通话状态监听')
if (that.isEnabled() && that.isReceiverRegistered) {
logUtils.debugInfo('移除phoneStateBroadcastReceiver')
context.unregisterReceiver(PHONE_STATE_RECEIVER)
}
// 生命周期结束后代码会自动移除 这里不用再移除了 避免并发修改异常
// engineService.unregisterEngineLifecycleCallback(this)
}
}
})
)
commonFunctions.registerOnEngineRemoved(function () {
logUtils.infoLog('脚本执行结束, 移除通话状态监听')
if (that.isEnabled() && that.isReceiverRegistered) {
logUtils.debugInfo('移除phoneStateBroadcastReceiver')
context.unregisterReceiver(PHONE_STATE_RECEIVER)
}
}, 'callState')

this.isEnabled = function () {
logUtils.debugInfo('当前启用状态:' + config.enable_call_state_control)
logUtils.debugInfo('通话状态监听功能当前启用状态:' + config.enable_call_state_control)
return config.enable_call_state_control
}

Expand Down Expand Up @@ -123,4 +108,4 @@ function CallStateListener () {
}
}

module.exports = new CallStateListener()
module.exports = new CallStateListener()
Loading

0 comments on commit 02d3386

Please sign in to comment.