events
events
Stability: 2-Stable
The events module provides an interface for monitoring mobile phone notifications, buttons, and touches. You can use it to cooperate with the automatic operation function to complete the automation work.
The events itself is an EventEmitter, but there are some built-in events, including key events, notification events, Toast events, etc.
It should be noted that the event processing is single-threaded and is still executed in the original thread. If the script body or other event processing has time-consuming operations, polling, etc., the event will not be processed in time (it will enter the event queue to wait for the script The main body or other event processing is completed before execution). E.g:
auto();
events.observeNotification();
events.on('toast', function(t){
//This code will not be executed
log(t);
});
while(true){
//Endless loop
}
events.emitter()
Return a new EventEmitter. This EventEmitter does not have any built-in events.
events.observeKey()
Enable key monitoring, such as the volume key and the home key. Key-press monitoring is implemented using an accessibility service. If the accessibility service is not enabled, an exception will be thrown and prompted to enable it.
Only after this function is successfully executed, the monitoring of key events such as onKeyDown
and onKeyUp
will be effective.
This function can only be used above Android 4.3.
events.onKeyDown(keyName, listener)
keyName
{string} The name of the key to be monitoredlistener
{Function} Button listener. The parameter is a KeyEvent.
Register a button monitoring function, which will be called when the button corresponding to keyName is pressed. Refer to Keys for available key names.
E.g:
//Enable button monitoring
events.observeKey();
//Monitor volume up key press
events.onKeyDown("volume_up", function(event){
toast("Volume up button was pressed");
});
//Monitor the menu key press
events.onKeyDown("menu", function(event){
toast("The menu button was pressed");
exit();
});
events.onKeyUp(keyName, listener)
keyName
{string} The name of the key to be monitoredlistener
{Function} Button listener. The parameter is a KeyEvent.
Register a button monitoring function, which will be called when the button corresponding to keyName pops up. Refer to Keys for available key names.
A complete key press includes key press and pop up. The press event is triggered at the "instant" when the finger presses a button, and the pop-up event is triggered when the finger releases the button.
E.g:
//Enable button monitoring
events.observeKey();
//Monitor volume down button pops up
events.onKeyDown("volume_down", function(event){
toast("Volume up button up");
});
//Monitor the Home button to pop up
events.onKeyDown("home", function(event){
toast("Home button pops up");
exit();
});
events.onceKeyDown(keyName, listener)
keyName
{string} The name of the key to be monitoredlistener
{Function} Button listener. The parameter is a KeyEvent
Register a button monitor function, which will be called when the button corresponding to keyName is pressed, and then the button monitor will be unregistered.
That is, the listener is only called once after the first keypress event after the onceKeyDown is called.
events.onceKeyUp(keyName, listener)
keyName
{string} The name of the key to be monitoredlistener
{Function} Button listener. The parameter is a KeyEvent
Register a button monitor function, which will be called when the button corresponding to keyName pops up, and then the button monitor will be unregistered.
That is, the listener is only called once after the first keypress event after the onceKeyUp is called.
events.removeAllKeyDownListeners(keyName)
keyName
{string} key name
Delete all listeners of the KeyDown (press) event of the key.
events.removeAllKeyUpListeners(keyName)
keyName
{string} key name
Delete all monitoring of the KeyUp event of the key.
events.setKeyInterceptionEnabled([key, ]enabled)
enabled
{boolean}key
{string} The key to be blocked
Set whether the key shield is enabled. The so-called button shielding refers to shielding the function of the original button, for example, the volume button can no longer adjust the volume, but at this time, the button can still be monitored through the button event.
If the parameter key is not added, all keys will be blocked.
For example, calling events.setKeyInterceptionEnabled(true)
will make the system's volume, home, and return keys no longer have the functions of adjusting volume, returning to the home page, and returning, but at this time, keystrokes can still be monitored through key events.
This function is usually combined with button monitoring. For example, if you want to monitor the volume key and make the volume adjustment box not pop up when the volume key is pressed, then:
events.setKeyInterceptionEnabled("volume_up", true);
events.observeKey();
events.onKeyDown("volume_up", ()=>{
log("Volume up button was pressed");
});
As long as a script blocks a certain key, the key will be blocked; when the script exits, all key blocks will be automatically unblocked.
events.observeTouch()
Enable screen touch monitoring. (Requires root privileges)
Only after this function is successfully executed, the touch event monitoring is effective.
Nothing will happen if you call this function without root privileges.
events.setTouchEventTimeout(timeout)
timeout
{number} The minimum interval between two touch events. The unit is milliseconds. The default is 10 milliseconds. If number is less than 0, it will be treated as 0.
Set the minimum time interval for the distribution of two touch events.
For example, if the interval is 10 milliseconds, after the previous touch event occurs and is processed by the registered listener, it will take at least 10 milliseconds before the next touch event can be dispatched and processed, and touches within these 10 milliseconds will be ignored.
It is recommended to increase this interval as much as possible while meeting the needs. A simple sliding action may trigger hundreds of touch events continuously. If the timeout is set too low, it may cause event congestion. It is strongly recommended not to set timeout to 0.
events.getTouchEventTimeout()
Returns the minimum time interval for touch events.
events.onTouch(listener)
listener
{Function} The function whose parameter is Point
Register a touch monitor function. Equivalent to on("touch", listener)
.
E.g:
//Enable touch monitoring
events.observeTouch();
//Register touch listener
events.onTouch(function(p){
//When a touch event occurs, print out the coordinates of the touched point
log(p.x + ", "+ p.y);
});
events.removeAllTouchListeners()
Delete all event listener functions.
Event:'key'
keyCode
{number} key valueevent
{KeyEvent} event
This event is triggered when a button is pressed or popped up. E.g:
auto();
events.observeKey();
events.on("key", function(keyCode, event){
//Handle key events
});
The parameter KeyCode of the listener includes:
keys.home
home keykeys.back
return keykeys.menu
menu keykeys.volume_up
volume up keykeys.volume_down
volume down key
E.g:
auto();
events.observeKey();
events.on("key", function(keyCode, event){
if(keyCode == keys.menu && event.getAction() == event.ACTION_UP){
toast("Menu button is pressed");
}
});
Event:'key_down'
keyCode
{number} key valueevent
{KeyEvent} event
This event is triggered when a button is pressed.
auto();
events.observeKey();
events.on("key_down", function(keyCode, event){
//Handle key press event
});
Event:'key_up'
keyCode
{number} key valueevent
{KeyEvent} event
This event will be triggered when a button pops up.
auto();
events.observeKey();
events.on("key_up", function(keyCode, event){
//Handle the key up event
});
Event:'exit`
This event is triggered when the script exits normally or abnormally. If an exception is thrown during event processing, the processing of the exit event will be immediately suspended (even if the exit event has multiple processing functions) and the exception will be printed in the console and log.
When a script stops running, all floating windows of the script will be closed, an exit event will be triggered, and then resources will be recovered. If there is an infinite loop in the processing of the exit event, subsequent resources cannot be recovered in time. At this time, the script will stay in the task list. If it is closed in the task list, the processing of the exit event will be forcibly ended and subsequent resources will be recycled.
log("Start running")
events.on("exit", function(){
log("End of operation");
});
log("The operation is about to end");
events.observeNotification()
Turn on notification monitoring. For example, QQ messages, WeChat messages, push notifications, etc.
Notification monitoring depends on the notification service. If the notification service is not running, it will throw an exception and jump to the notification permission opening interface. (Sometimes the notification service does not run even if the notification permission has been turned on, you need to close the permission and re-enable it at this time)
E.g:
events.observeNotification();
events.onNotification(function(notification){
log(notification.getText());
});
events.observeToast()
Turn on Toast monitoring.
Toast monitoring depends on the accessibility service, so this function will ensure that the accessibility service runs.
Event:'toast'
toast
{Object}*getText()
Get the text content of ToastgetPackageName()
Get the name of the application package that issued the Toast
This event is triggered when an application sends a toast (bubble message). But Auto.js software itself except toast.
For example, to record all toast applications:
events.observeToast();
events.onToast(function(toast){
log("Toast content: "+ toast.getText() +" package name: "+ toast.getPackageName());
});
Event:'notification'
notification
Notification notification object
This event is triggered when an application sends out a notification, and the parameter is Notification.
E.g:
events.observeNotification();
events.on("notification", function(n){
log("New notification received:\n Title: %s, Content: %s, \nPackage name: %s", n.getTitle(), n.getText(), n.getPackageName());
});
Notification
The notification object can obtain the notification details, including the notification title, content, package name, time, etc., and can also perform operations on the notification, such as clicking and deleting.
Notification.number
- {number}
Number of notifications. For example, when QQ continuously receives two messages, the number is 2.
Notification.when
- {number}
The timestamp of when the notification was sent can be used to construct a Date
object. E.g:
events.observeNotification();
events.on("notification", function(n){
log("Notification time is}" + new Date(n.when));
});
Notification.getPackageName()
- Return {string}
Get the name of the application package that sent the notification.
Notification.getTitle()
- Return {string}
Get the title of the notification.
Notification.getText()
- Return {string}
Get the content of the notification.
Notification.click()
Click the notification. For example, for a QQ message, click to enter the specific chat interface.
Notification.delete()
Delete the notification. The notification will disappear from the notification bar.
KeyEvent
Stability: 2-Stable
KeyEvent.getAction()
Returns the action of the event. include:
KeyEvent.ACTION_DOWN
press eventKeyEvent.ACTION_UP
pop-up event
KeyEvent.getKeyCode()
Returns the key value of the key. include:
KeyEvent.KEYCODE_HOME
home keyKeyEvent.KEYCODE_BACK
return keyKeyEvent.KEYCODE_MENU
menu keyKeyEvent.KEYCODE_VOLUME_UP
Volume up keyKeyEvent.KEYCODE_VOLUME_DOWN
Volume down key
KeyEvent.getEventTime()
- Return {number}
Returns the timestamp when the event occurred.
KeyEvent.getDownTime()
Returns the timestamp of the most recent press event. If it is a press event, it is the same as getEventTime()
.
KeyEvent.keyCodeToString(keyCode)
Convert the key value to a string. For example, KEYCODE_HOME is converted to "KEYCODE_HOME".
keys
Stability: 2-Stable
The names of all available keys in key events are:
volume_up
volume up keyvolume_down
volume down buttonhome
home screen keyback
return keymenu
menu key
EventEmitter
Stability: 2-Stable
EventEmitter.defaultMaxListeners
By default, up to 10 listeners can be registered for each event. The limit of a single EventEmitter instance can be changed using the emitter.setMaxListeners(n) method. The default value of all EventEmitter instances can be changed using the EventEmitter.defaultMaxListeners property.
Setting EventEmitter.defaultMaxListeners should be cautious because it will affect all EventEmitter instances, including those created before. Therefore, calling emitter.setMaxListeners(n) takes precedence over EventEmitter.defaultMaxListeners.
Note that unlike Node.js, this is a hard limit. The EventEmitter instance does not allow adding more listeners, and a TooManyListenersException will be thrown when the number of listeners exceeds the maximum.
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do something
emitter.setMaxListeners(Math.max(emitter.getMaxListeners()-1, 0));
});
EventEmitter.addListener(eventName, listener)
eventName
{any}listener
{Function}
Alias of emitter.on(eventName, listener).
EventEmitter.emit(eventName[, ...args])
eventName
{any}args
{any}
According to the registration order of the listeners, call each listener registered to the event named eventName synchronously, and pass in the provided parameters.
If the event has a listener, it returns true, otherwise it returns false.
EventEmitter.eventNames()
Returns an array listing the events of the trigger registered listener. The values in the array are strings or symbols.
const myEE = events.emitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Print: ['foo','bar', Symbol(symbol)]
EventEmitter.getMaxListeners()
Returns the current maximum listener limit value of EventEmitter. This value can be set by emitter.setMaxListeners(n) or the default is EventEmitter.defaultMaxListeners.
EventEmitter.listenerCount(eventName)
eventName
{string} The name of the event being monitored
Returns the number of listeners that are listening to the event named eventName.
EventEmitter.listeners(eventName)
eventName
{string}
Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Print: [[Function]]
EventEmitter.on(eventName, listener)
eventName
{any} event namelistener
{Function} callback function
Add the listener function to the end of the listener array for the event named eventName. It does not check whether the listener has been added. Calling multiple times and passing in the same eventName and listener will cause the listener to be added and called multiple times.
server.on('connection', (stream) => {
console.log('There is a connection!');
});
Returns an EventEmitter reference, which can be chained.
By default, event listeners will be called sequentially in the order they were added. The emitter.prependListener() method can be used to add event listeners to the beginning of the listener array.
const myEE = events.emitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// print:
// b
// a
EventEmitter.once(eventName, listener)#
eventName
{any} event namelistener
{Function} callback function
Add a one-shot listener function to the event named eventName. The next time the eventName event is triggered, the listener will be removed and then called.
server.once('connection', (stream) => {
console.log('First call!');
});
Returns an EventEmitter reference, which can be chained.
By default, event listeners will be called sequentially in the order they were added. The emitter.prependOnceListener() method can be used to add event listeners to the beginning of the listener array.
const myEE = events.emitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// print:
// b
// a
EventEmitter.prependListener(eventName, listener)
eventName
{any} event namelistener
{Function} callback function
Add the listener function to the beginning of the listener array for the event named eventName. It does not check whether the listener has been added. Calling multiple times and passing in the same eventName and listener will cause the listener to be added and called multiple times.
server.prependListener('connection', (stream) => {
console.log('There is a connection!');});
Returns an EventEmitter reference, which can be chained.
EventEmitter.prependOnceListener(eventName, listener)
eventName
{any} event namelistener
{Function} callback function
Add a one-shot listener function to the beginning of the listener array for the event named eventName. The next time the eventName event is triggered, the listener will be removed and then called.
server.prependOnceListener('connection', (stream) => {
console.log('First call!');
});
Returns an EventEmitter reference, which can be chained.
EventEmitter.removeAllListeners([eventName])
eventName
{any}
Remove all or the listeners of the specified eventName.
Note that it is a bad practice to remove listeners added elsewhere in the code, especially when the EventEmitter instance is created by other components or modules.
Returns an EventEmitter reference, which can be chained.
EventEmitter.removeListener(eventName, listener)
eventName
{any}listener
{Function}
Remove the specified listener from the listener array for the event named eventName.
const callback = (stream) => {
console.log('There is a connection!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener will only remove at most one listener instance from the listener array. If any single listener is added to the listener array of the specified eventName multiple times, removeListener must be called multiple times to remove each instance.
Note that once an event is triggered, all listeners bound to it will be triggered in sequence. This means that any call to removeListener() or removeAllListeners() will not remove them from emit() after the event is triggered and before the last listener has finished executing. Subsequent events will happen as expected.
const myEmitter = events.emitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes the listener callbackB, but it will still be called.
// The trigger is the internal listener array is [callbackA, callbackB]
myEmitter.emit('event');
// print:
// A
// B
// callbackB is removed.
// The internal listener array is [callbackA]
myEmitter.emit('event');
// print:
// A
Because the listener is managed using an internal array, calling it will change the position index of any listener registered after the listener is removed. Although this does not affect the call sequence of the listeners, it means that a copy of the listener array returned by the emitter.listeners() method needs to be recreated.
Returns an EventEmitter reference, which can be chained.
EventEmitter.setMaxListeners(n)
n
{number}
By default, if more than 10 listeners are added for a particular event, EventEmitter will print a warning. This limitation helps to find memory leaks. However, not all events are limited to 10. The emitter.setMaxListeners() method allows to modify the limits of the specified EventEmitter instance. A value of Infinity (or 0) indicates that the number of listeners is not limited.
Returns an EventEmitter reference, which can be chained.
events.broadcast: Broadcast between scripts
In addition to the ScriptEngine.emit()
method provided by the engines module, the communication between scripts can also use the broadcast provided by the events module.
events.broadcast itself is an EventEmitter, but its events are shared between scripts, all scripts can send and listen to these events; event processing will be executed in the main thread of the script (the function onThisThread(eventName, ... may be added later) args)
to provide the ability to execute in other threads).
For example, sending a broadcast hello in a script:
events.broadcast.emit("hello", "小明");
Monitor and process in other scripts:
events.broadcast.on("hello", function(name){
toast("Hello, "+ name);
});
//Keep the script running
setInterval(()=>{}, 1000);