work_manager


CloudControl Pro 9 Docs / work_manager

work_manager

This module is used to manage tasks, which can be run automatically at certain time or event, or when a file is changed.

When adding a task, it is recommended to add a request to ignore battery optimizations.

"nodejs";
const power_manager = require("power_manager");
if (!power_manager.isIgnoringBatteryOptimizations()) {
    power_manager.requestIgnoreBatteryOptimizations();
}

Table of contents

Interfaces

Type Aliases

Functions

Type Aliases

DateTime

Ƭ DateTime: number | string | Date

DateTime type, could be a number which represents millisecond timestamp; or be a string which represents standard time format; or a Date object.


DaysOfWeek

Ƭ DaysOfWeek: "Sunday" | "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "一" | "二" | "三" | "四" | "五" | "六" | "日"


TaskType

Ƭ TaskType: "TimedTask" | "IntentTask"

Functions

addActivityIntentTask

addActivityIntentTask(task): Promise<Task>

Add a task to run when an activity intent is handled.

For example, when an activity intent is handled, such as opening a file in file manager, the task will be run.

The first parameter is action, which decides what action will trigger the task. For example:

  • android.intent.action.VIEW: When an activity intent is handled, such as opening a file in file manager, the task will be run.
  • android.intent.action.SEND: When an activity intent is handled, such as sharing a file, the task will be run.
  • More actions can be found in Intent: Actionopen in new window

The second parameter is dataType, which decides what type of file will trigger the task. For example:

  • /: All files
  • application/vnd.android.package-archive: apk files
  • text/plain: Text files
  • video/*: Video files
  • image/*: Image files

The following code will add a task to run when an activity intent is handled to open a text file:

const { addActivityIntentTask } = require("work_manager");

addActivityIntentTask({
  path: "/sdcard/Scripts/handle_text.js",
  action: 'android.intent.action.VIEW',
  dataType: "text/plain"
}).then(task => console.log(`Task ${task} added`));

The following code is the content of handle_text.js, which will read the file content and print it:

// handle_text.js
"nodejs";
const { myEngine } = require('engines');
const { getPathFromUri } = require('app');
const { readFileSync } = require('fs');
const intent = myEngine().execArgv.intent;
if (!intent) {
    process.exit();
}
const uri = intent.getUri();
const file = getPathFromUri(uri);
console.log(file);
console.log(readFileSync(file, 'utf8'));

Parameters

Name Type
task IntentTaskConfig

Returns

Promise<Task>


addBroadcastIntentTask

addBroadcastIntentTask(task): Promise<Task>

Add a broadcast intent task, will run when a specific event (broadcast) happens.

The most important parameter is the broadcast event's Action. System will send out a specific Action broadcast when a specific event (such as battery changed) happens.

For example, create a task that runs a script when battery changed:

"nodejs";
const { android } = require('rhino').Packages;
const Intent = android.content.Intent;
const { addBroadcastIntentTask } = require("work_manager");
addBroadcastIntentTask({
   path: "/path/to/script.js",
  action: Intent.ACTION_BATTERY_CHANGED,
}).then(task => console.log(`Task ${task} added`));

You can find most of Android system's built-in Intent Action in Intent: Actionopen in new window in Android document. Some system components also define their own Actions, for example, ConnectivityManager.CONNECTIVITY_ACTION (use require('ConnectivityManager') to import it).

Here are some common broadcast Actions:

  • org.autojs.autojs.action.startup : CloudControl startup
  • Intent.ACTION_BOOT_COMPLETED : Boot completed
  • Intent.ACTION_SCREEN_OFF : Screen off
  • Intent.ACTION_SCREEN_ON : Screen on
  • Intent.ACTION_USER_PRESENT : Screen unlock
  • Intent.ACTION_BATTERY_CHANGED : Battery changed
  • Intent.ACTION_POWER_CONNECTED : Power connected
  • Intent.ACTION_POWER_DISCONNECTED : Power disconnected
  • ConnectivityManager.CONNECTIVITY_ACTION : Network connectivity changed
  • Intent.ACTION_PACKAGE_ADDED : Package added
  • Intent.ACTION_PACKAGE_REMOVED : Package removed
  • Intent.ACTION_PACKAGE_REPLACED : Package replaced
  • Intent.ACTION_HEADSET_PLUG : Headset plugged
  • Intent.ACTION_CONFIGURATION_CHANGED : Configuration changed
  • Intent.ACTION_TIME_TICK : Time tick on every minute

When the task runs, you can get the Intent object by require('engines').myEngine().execArgv.intent.

The following is an example of getting battery level when battery changed task is run:

"nodejs";
const { myEngine } = require('engines');
const { android } = require('rhino').Packages;

const intent = myEngine().execArgv.intent;
if (!intent) {
   process.exit();
}
const BatteryManager = android.os.BatteryManager;
const level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
console.log("Battery:", level);

Parameters

Name Type Description
task IntentTaskConfig Broadcast intent task configuration

Returns

Promise<Task>

Promise of added task


addDailyTask

addDailyTask(task): Promise<Task>

Add a timed task which runs once a day. The time parameter will only keep the time of the day, ignore the year, month and day.

For example, create a timed task which runs at 1:14 PM every day.

Example

"nodejs";
const { addDailyTask } = require("work_manager");
addDailyTask({
    path: "/path/to/script.js",
    time: new Date(0, 0, 0, 13, 14, 0),
})).then(task => console.log(task));

Parameters

Name Type Description
task TimedTaskConfig The configuration of the timed task.

Returns

Promise<Task>


addIntentTask

addIntentTask(task): Promise<Task>

Add an intent task. There are two types:

  • Broadcast intent task: run at a specific broadcast event.
  • Activity intent task: run when opening external files in an external application. For example, when opening files in the file manager, or when sharing files or text in other applications, if the user selects CloudControl, the corresponding task will be triggered.

It is recommended to use addBroadcastIntentTask and addActivityIntentTask instead of using this function to add tasks.

Parameters

Name Type
task IntentTaskConfig

Returns

Promise<Task>


addOneTimeTask

addOneTimeTask(task): Promise<Task>

Add a timed task which runs once.

For example, create a timed task which runs on May 21, 2021 at 1:14 PM.

Example

"nodejs";
const { addOneTimeTask } = require("work_manager");
addOneTimeTask({
    path: "/sdcard/to/script.js",
    time: new Date(2021, 5, 21, 13, 14, 0),
}).then(task => console.log(task));

Parameters

Name Type
task TimedTaskConfig

Returns

Promise<Task>


addWeeklyTask

addWeeklyTask(task): Promise<Task>

Add a timed task which runs every week.

For example, create a timed task which runs every Monday and Tuesday at 1:14 PM.

Example

"nodejs";
const { addWeeklyTask } = require("work_manager");
addWeeklyTask({
    path: "/sdcard/脚本/test.js",
    // Mon Jun 21 2021 13:14:00 GMT+0800 
    time: 1624252440000,
    daysOfWeek: ['Monday', 'Tuesday'],
}).then(task => console.log(task));

Parameters

Name Type Description
task WeeklyTaskConfig The configuration of the timed task.

Returns

Promise<Task>


getIntentTask

getIntentTask(id): Promise<Task | null>

Get the intent task by task ID.

See

Task.id

Parameters

Name Type Description
id number Task ID

Returns

Promise<Task | null>

The Promise of the task, if not found, resolve null


getTimedTask

getTimedTask(id): Promise<Task | null>

Get the timed task by task ID.

See

Task.id

Parameters

Name Type Description
id number Task ID

Returns

Promise<Task | null>

The Promise of the task, if not found, resolve null


queryIntentTasks

queryIntentTasks(query?): Promise<Task[]>

Query intent tasks by script path or Intent Action.

Example

"nodejs";
const { queryIntentTasks, addBroadcastIntentTask } = require("work_manager");
async function main() {
    const task = await addBroadcastIntentTask({
        path: "/sdcard/to/script.js",
        action: Intent.ACTION_BATTERY_CHANGED,
    });
    // Query all intent tasks
    const tasks = await queryIntentTasks();
    console.log(tasks);
}
main();

Parameters

Name Type Description
query? IntentTaskQuery intent task query conditions, empty to query all tasks

Returns

Promise<Task[]>


queryTimedTasks

queryTimedTasks(query?): Promise<Task[]>

Query timed tasks by script path.

Example

"nodejs";
const work_manager = require('work-manager');

const file = "/path/to/script.js";
async function main() {
const task = await work_manager.addWeeklyTask({
    path: file,
    time: 1624252440000,
    daysOfWeek: ['Sunday'],
});
const tasks = await work_manager.queryTimedTasks({
    path: file
});
tasks.forEach(t => {
    console.log("delete:", t);
    console.log(await work_manager.removeTimedTask(t.id));
});
}

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `query?` | [`TimedTaskQuery`](../interfaces/work_manager.TimedTaskQuery.md) | timed task query conditions, empty to query all tasks |

#### Returns

`Promise`<`Task`[]\>

___

### removeIntentTask

▸ **removeIntentTask**(`id`): `Promise`<`boolean`\>

Delete an intent task by id.

**`See`**

Task.id

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `number` | The id of the task. |

#### Returns

`Promise`<`boolean`\>

Promise that indicates whether the task is deleted successfully. If the task does not exist, resolve false, otherwise resolve true.

___

### removeTimedTask

▸ **removeTimedTask**(`id`): `Promise`<`boolean`\>

Delete a timed task by id.

**`See`**

Task.id

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `number` | The id of the task. |

#### Returns

`Promise`<`boolean`\>

Promise that indicates whether the task is deleted successfully. If the task does not exist, resolve false, otherwise resolve true.