未验证 提交 b213bdb5 编写于 作者: O openharmony_ci 提交者: Gitee

!20741 翻译完成 20471+19599+20078+20395+19795

Merge pull request !20741 from ester.zhou/TR-20471
...@@ -154,15 +154,15 @@ Switches to another input method. This API uses a promise to return the result. ...@@ -154,15 +154,15 @@ Switches to another input method. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
|target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| |target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------- | ---------------------------- | | ----------------------------------------- | ---------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.|
**Error codes** **Error codes**
...@@ -218,7 +218,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb ...@@ -218,7 +218,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb
Switches to another subtype of the current input method. This API uses an asynchronous callback to return the result. Switches to another subtype of the current input method. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECT_IME_ABILITY<br>**NOTE** <br>- API version 10 and later: This API can be called by system applications and the current input method application.<br>- API version 9: This API can be called by system applications only. **Required permissions**: ohos.permission.CONNECT_IME_ABILITY
> **NOTE**
>
> - API version 10 and later: This API can be called by system applications and the current input method application.
> - API version 9: This API can be called by system applications only.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -274,7 +279,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise&lt;boolean& ...@@ -274,7 +279,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise&lt;boolean&
Switches to another subtype of the current input method. This API uses a promise to return the result. Switches to another subtype of the current input method. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECT_IME_ABILITY<br>**NOTE** <br>- API version 10 and later: This API can be called by system applications and the current input method application.<br>- API version 9: This API can be called by system applications only. **Required permissions**: ohos.permission.CONNECT_IME_ABILITY
> **NOTE**
>
> - API version 10 and later: This API can be called by system applications and the current input method application.
> - API version 9: This API can be called by system applications only.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -705,7 +715,7 @@ try { ...@@ -705,7 +715,7 @@ try {
attach(showKeyboard: boolean, textConfig: TextConfig): Promise&lt;void&gt; attach(showKeyboard: boolean, textConfig: TextConfig): Promise&lt;void&gt;
Attaches a self-drawing component to the input method. This API uses an asynchronous callback to return the result. Attaches a self-drawing component to the input method. This API uses a promise to return the result.
An input method can use the features provided by the input method framework only when it has a self-drawing component attached to it. An input method can use the features provided by the input method framework only when it has a self-drawing component attached to it.
...@@ -797,7 +807,7 @@ showTextInput(): Promise&lt;void&gt; ...@@ -797,7 +807,7 @@ showTextInput(): Promise&lt;void&gt;
Enters the text editing mode. This API uses a promise to return the result. Enters the text editing mode. This API uses a promise to return the result.
This API can be called to start the soft keyboard after the editor component is bound to the input method. This API can be called to start the soft keyboard after the editor component is attached to the input method.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -1692,11 +1702,11 @@ Disables listening for the text insertion event of the input method. ...@@ -1692,11 +1702,11 @@ Disables listening for the text insertion event of the input method.
inputMethodController.off('insertText'); inputMethodController.off('insertText');
``` ```
### on('deleteLeft' | 'deleteRight')<sup>10+</sup> ### on('deleteLeft')<sup>10+</sup>
on(type: 'deleteLeft' | 'deleteRight', callback: (length: number) => void): void on(type: 'deleteLeft', callback: (length: number) => void): void
Enables listening for the delete-to-the-left or delete-to-the-right event of the input method. This API uses an asynchronous callback to return the result. Enables listening for the backward delete event. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -1704,8 +1714,8 @@ Enables listening for the delete-to-the-left or delete-to-the-right event of the ...@@ -1704,8 +1714,8 @@ Enables listening for the delete-to-the-left or delete-to-the-right event of the
| Name | Type| Mandatory| Description| | Name | Type| Mandatory| Description|
| -------- | ----- | ---- | ----- | | -------- | ----- | ---- | ----- |
| type | string | Yes | Listening type.<br>- The value **'deleteLeft'** indicates the delete-to-the-left event.<br>- The value **'deleteRight'** indicates the delete-to-the-right event.| | type | string | Yes | Listening type.<br>The value **'deleteLeft'** indicates the backward delete event.|
| callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted to the left or to the right.<br>Your application needs to operate the content in the edit box based on the length returned in the callback.| | callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted backward.<br>Your application needs to operate the content in the edit box based on the length returned in the callback.|
**Error codes** **Error codes**
...@@ -1725,7 +1735,34 @@ try { ...@@ -1725,7 +1735,34 @@ try {
} catch(err) { } catch(err) {
console.error(`Failed to subscribe deleteLeft: ${JSON.stringify(err)}`); console.error(`Failed to subscribe deleteLeft: ${JSON.stringify(err)}`);
} }
```
### on('deleteRight')<sup>10+</sup>
on(type: 'deleteRight', callback: (length: number) => void): void
Enables listening for the forward delete event. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type| Mandatory| Description|
| -------- | ----- | ---- | ----- |
| type | string | Yes | Listening type.<br>The value **'deleteRight'** indicates the forward delete event.|
| callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted forward.<br>Your application needs to operate the content in the edit box based on the length returned in the callback.|
**Error codes**
For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md).
| Error Code ID| Error Message |
| -------- | -------------------------------------- |
| 12800009 | input method client is detached. |
**Example**
```js
try { try {
inputMethodController.on('deleteRight', (length) => { inputMethodController.on('deleteRight', (length) => {
console.log(`Succeeded in subscribing deleteRight, length: ${length}`); console.log(`Succeeded in subscribing deleteRight, length: ${length}`);
...@@ -1734,12 +1771,11 @@ try { ...@@ -1734,12 +1771,11 @@ try {
console.error(`Failed to subscribe deleteRight: ${JSON.stringify(err)}`); console.error(`Failed to subscribe deleteRight: ${JSON.stringify(err)}`);
} }
``` ```
### off('deleteLeft')<sup>10+</sup>
### off('deleteLeft' | 'deleteRight')<sup>10+</sup> off(type: 'deleteLeft'): void
off(type: 'deleteLeft' | 'deleteRight'): void
Disables listening for the delete-to-the-left or delete-to-the-right event of the input method. Disables listening for the backward delete event.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -1747,12 +1783,31 @@ Disables listening for the delete-to-the-left or delete-to-the-right event of th ...@@ -1747,12 +1783,31 @@ Disables listening for the delete-to-the-left or delete-to-the-right event of th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>- The value **'deleteLeft'** indicates the delete-to-the-left event.<br>- The value **'deleteRight'** indicates the delete-to-the-right event.| | type | string | Yes | Listening type.<br>The value **'deleteLeft'** indicates the backward delete event.|
**Example** **Example**
```js ```js
inputMethodController.off('deleteLeft'); inputMethodController.off('deleteLeft');
```
### off('deleteRight')<sup>10+</sup>
off(type: 'deleteRight'): void
Disables listening for the forward delete event.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'deleteRight'** indicates the forward delete event.|
**Example**
```js
inputMethodController.off('deleteRight'); inputMethodController.off('deleteRight');
``` ```
...@@ -2062,6 +2117,180 @@ Disables listening for the select-by-cursor-movement event. ...@@ -2062,6 +2117,180 @@ Disables listening for the select-by-cursor-movement event.
inputMethodController.off('selectByMovement'); inputMethodController.off('selectByMovement');
``` ```
### on('getLeftTextOfCursor')<sup>10+</sup>
on(type: 'getLeftTextOfCursor', callback: (length: number) => string): void;
Enables listening for the event of obtaining the length of text deleted backward. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----- | ---- | ------ |
| type | string | Yes | Listening type.<br>The value **'getLeftTextOfCursor'** indicates the event of obtaining the length of text deleted backward.|
| callback | (length: number) => string | Yes | Callback used to obtain the text of the specified length deleted backward.<br>In this callback, obtain the text of the specified length on the left of the cursor in the latest state of the edit box and return the text.|
**Example**
```js
try {
inputMethodController.on('getLeftTextOfCursor', (length) => {
console.info(`Succeeded in subscribing getLeftTextOfCursor, length: ${length}`);
let text:string = "";
return text;
});
} catch(err) {
console.error(`Failed to subscribe getLeftTextOfCursor. Code: ${err.code}, message: ${err.message}`);
}
```
### off('getLeftTextOfCursor')<sup>10+</sup>
off(type: 'getLeftTextOfCursor', callback?: (length: number) => string): void;
Disables listening for the event of obtaining the length of text deleted backward. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'getLeftTextOfCursor'** indicates the event of obtaining the length of text deleted backward.|
| callback | (length: number) => string | No | Callback used to obtain the text of the specified length deleted backward. The value must be the same as that passed in by the **on** API.|
**Example**
```js
try {
inputMethodController.off('getLeftTextOfCursor', (length) => {
console.info(`Succeeded in unsubscribing getLeftTextOfCursor, length: ${length}`);
let text:string = "";
return text;
});
} catch(err) {
console.error(`Failed to unsubscribing getLeftTextOfCursor. Code: ${err.code}, message: ${err.message}`);
}
```
### on('getRightTextOfCursor')<sup>10+</sup>
on(type: 'getRightTextOfCursor', callback: (length: number) => string): void;
Enables listening for the event of obtaining the length of text deleted forward. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----- | ---- | ------ |
| type | string | Yes | Listening type.<br>The value **'getRightTextOfCursor'** indicates the event of obtaining the length of text deleted forward.|
| callback | (length: number) => string | Yes | Callback used to obtain the text of the specified length deleted forward.<br>In this callback, obtain the text of the specified length on the right of the cursor in the latest state of the edit box and return the text.|
**Example**
```js
try {
inputMethodController.on('getRightTextOfCursor', (length) => {
console.info(`Succeeded in subscribing getRightTextOfCursor, length: ${length}`);
let text:string = "";
return text;
});
} catch(err) {
console.error(`Failed to subscribe getRightTextOfCursor. Code: ${err.code}, message: ${err.message}`);
}
```
### off('getRightTextOfCursor')<sup>10+</sup>
off(type: 'getRightTextOfCursor', callback?: (length: number) => string): void;
Disables listening for the event of obtaining the length of text deleted forward. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'getRightTextOfCursor'** indicates the event of obtaining the length of text deleted forward.|
| callback | (length: number) => string | No | Callback used to obtain the text of the specified length deleted forward. The value must be the same as that passed in by the **on** API.|
**Example**
```js
try {
inputMethodController.off('getRightTextOfCursor', (length) => {
console.info(`Succeeded in unsubscribing getRightTextOfCursor, length: ${length}`);
let text:string = "";
return text;
});
} catch(err) {
console.error(`Failed to unsubscribing getRightTextOfCursor. Code: ${err.code}, message: ${err.message}`);
}
```
### on('getTextIndexAtCursor')<sup>10+</sup>
on(type: 'getTextIndexAtCursor', callback: () => number): void;
Enables listening for the event of obtaining the index of text at the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----- | ---- | ------ |
| type | string | Yes | Listening type.<br>The value **'getTextIndexAtCursor'** indicates the event of obtaining the index of text at the cursor.|
| callback | () => number | Yes | Callback used to obtain the index of text at the cursor.<br>In this callback, obtain the index of text at the cursor in the latest state of the edit box and return the index.|
**Example**
```js
try {
inputMethodController.on('getTextIndexAtCursor', () => {
console.info(`Succeeded in subscribing getTextIndexAtCursor.`);
let index:number = 0;
return index;
});
} catch(err) {
console.error(`Failed to subscribe getTextIndexAtCursor. Code: ${err.code}, message: ${err.message}`);
}
```
### off('getTextIndexAtCursor')<sup>10+</sup>
off(type: 'getTextIndexAtCursor', callback?: () => number): void;
Disables listening for the event of obtaining the index of text at the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'getTextIndexAtCursor'** indicates the event of obtaining the index of text at the cursor.|
| callback | () => number | No | Callback used to obtain the index of text at the cursor. The value must be the same as that passed in by the **on** API.|
**Example**
```js
try {
inputMethodController.off('getTextIndexAtCursor', () => {
console.info(`Succeeded in unsubscribing getTextIndexAtCursor.`);
let index:number = 0;
return index;
});
} catch(err) {
console.error(`Failed to unsubscribing getTextIndexAtCursor. Code: ${err.code}, message: ${err.message}`);
}
```
## InputMethodSetting<sup>8+</sup> ## InputMethodSetting<sup>8+</sup>
In the following API examples, you must first use [getSetting](#inputmethodgetsetting9) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. In the following API examples, you must first use [getSetting](#inputmethodgetsetting9) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance.
...@@ -2110,11 +2339,11 @@ Disables listening for the input method and subtype change event. This API uses ...@@ -2110,11 +2339,11 @@ Disables listening for the input method and subtype change event. This API uses
inputMethodSetting.off('imeChange'); inputMethodSetting.off('imeChange');
``` ```
### on('imeShow'|'imeHide')<sup>10+</sup> ### on('imeShow')<sup>10+</sup>
on(type: 'imeShow'|'imeHide', callback: (info: Array\<InputWindowInfo>) => void): void on(type: 'imeShow', callback: (info: Array\<InputWindowInfo>) => void): void
Enables listening for a soft keyboard visibility event of the input method. This API uses an asynchronous callback to return the result. Enables listening for the show event of the soft keyboard. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -2124,7 +2353,7 @@ Enables listening for a soft keyboard visibility event of the input method. This ...@@ -2124,7 +2353,7 @@ Enables listening for a soft keyboard visibility event of the input method. This
| Name | Type| Mandatory| Description| | Name | Type| Mandatory| Description|
| -------- | ---- | ---- | ---- | | -------- | ---- | ---- | ---- |
| type | string | Yes| Listening type.<br>- The value **'imeShow'** indicates the soft keyboard display event.<br>- The value **'imeHide'** indicates the soft keyboard hiding event.| | type | string | Yes| Listening type.<br>The value **'imeShow'** indicates the show event of the soft keyboard.|
| callback | (info: Array\<InputWindowInfo>) => void | Yes| Callback used to return the information about the soft keyboard of the input method.| | callback | (info: Array\<InputWindowInfo>) => void | Yes| Callback used to return the information about the soft keyboard of the input method.|
**Example** **Example**
...@@ -2135,11 +2364,36 @@ inputMethodSetting.on('imeShow', (info) => { ...@@ -2135,11 +2364,36 @@ inputMethodSetting.on('imeShow', (info) => {
}); });
``` ```
### off('imeShow'|'imeHide')<sup>10+</sup> ### on('imeHide')<sup>10+</sup>
on(type: 'imeHide', callback: (info: Array\<InputWindowInfo>) => void): void
Enables listening for the hide event of the soft keyboard. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type| Mandatory| Description|
| -------- | ---- | ---- | ---- |
| type | string | Yes| Listening type.<br>The value **'imeHide'** indicates the hide event of the soft keyboard.|
| callback | (info: Array\<InputWindowInfo>) => void | Yes| Callback used to return the information about the soft keyboard of the input method.|
**Example**
```js
inputMethodSetting.on('imeHide', (info) => {
console.info('Succeeded in subscribing imeHide event.');
});
```
### off('imeShow')<sup>10+</sup>
off(type: 'imeShow'|'imeHide', callback?: (info: Array\<InputWindowInfo>) => void): void off(type: 'imeShow', callback?: (info: Array\<InputWindowInfo>) => void): void
Disables listening for a soft keyboard visibility event of the input method. Disables listening for the show event of the soft keyboard.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -2149,7 +2403,7 @@ Disables listening for a soft keyboard visibility event of the input method. ...@@ -2149,7 +2403,7 @@ Disables listening for a soft keyboard visibility event of the input method.
| Name | Type| Mandatory| Description | | Name | Type| Mandatory| Description |
| -------- | ---- | ---- | ------ | | -------- | ---- | ---- | ------ |
| type | string | Yes| Listening type.<br>- The value **'imeShow'** indicates the soft keyboard display event.<br>- The value **'imeHide'** indicates the soft keyboard hiding event.| | type | string | Yes| Listening type.<br>The value **'imeShow'** indicates the show event of the soft keyboard.|
| callback | (info: Array\<InputWindowInfo>) => void | No| Callback used for disable listening. If this parameter is not specified, all callbacks corresponding to the set event are invoked.| | callback | (info: Array\<InputWindowInfo>) => void | No| Callback used for disable listening. If this parameter is not specified, all callbacks corresponding to the set event are invoked.|
**Example** **Example**
...@@ -2158,6 +2412,29 @@ Disables listening for a soft keyboard visibility event of the input method. ...@@ -2158,6 +2412,29 @@ Disables listening for a soft keyboard visibility event of the input method.
inputMethodSetting.off('imeShow'); inputMethodSetting.off('imeShow');
``` ```
### off('imeHide')<sup>10+</sup>
off(type: 'imeHide', callback?: (info: Array\<InputWindowInfo>) => void): void
Disables listening for the hide event of the soft keyboard.
**System API**: This is a system API.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type| Mandatory| Description |
| -------- | ---- | ---- | ------ |
| type | string | Yes| Listening type.<br>The value **'imeHide'** indicates the hide event of the soft keyboard.|
| callback | (info: Array\<InputWindowInfo>) => void | No| Callback used for disable listening. If this parameter is not specified, all callbacks corresponding to the set event are invoked.|
**Example**
```js
inputMethodSetting.off('imeHide');
```
### listInputMethodSubtype<sup>9+</sup> ### listInputMethodSubtype<sup>9+</sup>
listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: AsyncCallback&lt;Array&lt;InputMethodSubtype&gt;&gt;): void listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: AsyncCallback&lt;Array&lt;InputMethodSubtype&gt;&gt;): void
......
...@@ -504,7 +504,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and ...@@ -504,7 +504,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and
| Error Code ID | Error Message | | Error Code ID | Error Message |
| ---------- | ----------------------------- | | ---------- | ----------------------------- |
| 12800004 | not an input method extension | | 12800004 | not an input method extension. |
**Example** **Example**
...@@ -552,7 +552,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and ...@@ -552,7 +552,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and
| Error Code ID | Error Message | | Error Code ID | Error Message |
| ---------- | ----------------------------- | | ---------- | ----------------------------- |
| 12800004 | not an input method extension | | 12800004 | not an input method extension. |
**Example** **Example**
...@@ -728,6 +728,57 @@ inputMethodEngine.getKeyboardDelegate().off('keyDown', (keyEvent) => { ...@@ -728,6 +728,57 @@ inputMethodEngine.getKeyboardDelegate().off('keyDown', (keyEvent) => {
}); });
``` ```
### on('keyEvent')<sup>10+</sup>
on(type: 'keyEvent', callback: (event: InputKeyEvent) => boolean): void
Enables listening for a keyboard event. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'keyEvent'** indicates the keyboard event.|
| callback | function | Yes | Callback used to return the result.<br>- The input parameter, of the [InputKeyEvent](js-apis-keyevent.md#KeyEvent) type, indicates the key event information.<br>- If the event is consumed by the event subscriber, **true** is returned. Otherwise, **false** is returned.|
**Example**
```js
inputMethodEngine.getKeyboardDelegate().on('keyEvent', (keyEvent) => {
console.log('inputMethodEngine keyEvent.action:' + JSON.stringify(keyEvent.action));
console.log('inputMethodEngine keyEvent.key.code:' + JSON.stringify(keyEvent.key.code));
console.log('inputMethodEngine keyEvent.ctrlKey:' + JSON.stringify(keyEvent.ctrlKey));
return true;
});
```
### off('keyEvent')<sup>10+</sup>
off(type: 'keyEvent', callback?: (event: InputKeyEvent) => boolean): void
Disables listening for a keyboard event. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>The value **'keyEvent'** indicates the keyboard event.|
| callback | function | No | Callback to be unregistered.<br>- The input parameter, of the [InputKeyEvent](js-apis-keyevent.md#KeyEvent) type, indicates the key event information.<br>- If the event is consumed by the event subscriber, **true** is returned. Otherwise, **false** is returned.<br>- This parameter is optional. If this parameter is not specified, all callbacks registered for the event will be unregistered.|
**Example**
```js
inputMethodEngine.getKeyboardDelegate().off('keyEvent', (keyEvent) => {
console.log('This is a callback function which will be deregistered.');
return true;
});
inputMethodEngine.getKeyboardDelegate().off('keyEvent');
```
### on('cursorContextChange') ### on('cursorContextChange')
on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void
...@@ -1147,7 +1198,7 @@ This API does not work on panels in the FLG_FIXED state. ...@@ -1147,7 +1198,7 @@ This API does not work on panels in the FLG_FIXED state.
```js ```js
try { try {
let promise = windowClass.moveTo(300, 300); let promise = panel.moveTo(300, 300);
promise.then(() => { promise.then(() => {
console.log('Succeeded in moving the panel.'); console.log('Succeeded in moving the panel.');
}).catch((err) =>{ }).catch((err) =>{
...@@ -1260,11 +1311,11 @@ promise.then(() => { ...@@ -1260,11 +1311,11 @@ promise.then(() => {
}); });
``` ```
### on<sup>10+</sup> ### on('show')<sup>10+</sup>
on(type: 'show' | 'hide', callback: () => void): void on(type: 'show', callback: () => void): void
Enables listening for a panel visibility event. This API uses an asynchronous callback to return the result. Enables listening for the show event of this panel. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -1272,7 +1323,7 @@ Enables listening for a panel visibility event. This API uses an asynchronous ca ...@@ -1272,7 +1323,7 @@ Enables listening for a panel visibility event. This API uses an asynchronous ca
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | -------- | | -------- | ---------------------- | ---- | -------- |
| type | 'show'\|'hide' | Yes| Listening type.<br>- The value **'show'** indicates the panel display event.<br>- The value **'hide'** indicates the panel hiding event.| | type | string | Yes| Listening type.<br>The value **'show'** indicates the show event.|
| callback | () => void | Yes | Callback used to return the result.| | callback | () => void | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -1283,11 +1334,11 @@ panel.on('show', () => { ...@@ -1283,11 +1334,11 @@ panel.on('show', () => {
}); });
``` ```
### off<sup>10+</sup> ### on('hide')<sup>10+</sup>
off(type: 'show' | 'hide', callback?: () => void): void on(type: 'hide', callback: () => void): void
Disables listening for a panel visibility event. This API uses an asynchronous callback to return the result. Enables listening for the hide event of this panel. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
...@@ -1295,7 +1346,30 @@ Disables listening for a panel visibility event. This API uses an asynchronous c ...@@ -1295,7 +1346,30 @@ Disables listening for a panel visibility event. This API uses an asynchronous c
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | -------- | | -------- | ---------------------- | ---- | -------- |
| type | 'show'\|'hide' | Yes| Listening type.<br>- The value **'show'** indicates the panel display event.<br>- The value **'hide'** indicates the panel hiding event.| | type | string | Yes| Listening type.<br>The value **'hide'** indicates the hide event.|
| callback | () => void | Yes | Callback used to return the result.|
**Example**
```js
panel.on('hide', () => {
console.log('Panel is hiding.');
});
```
### off('show')<sup>10+</sup>
off(type: 'show', callback?: () => void): void
Disables listening for the show event of this panel. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | -------- |
| type | string | Yes| Listening type.<br>The value **'show'** indicates the show event.|
| callback | () => void | No | Callback used to return the result.| | callback | () => void | No | Callback used to return the result.|
**Example** **Example**
...@@ -1304,6 +1378,27 @@ Disables listening for a panel visibility event. This API uses an asynchronous c ...@@ -1304,6 +1378,27 @@ Disables listening for a panel visibility event. This API uses an asynchronous c
panel.off('show'); panel.off('show');
``` ```
### off('hide')<sup>10+</sup>
off(type: 'hide', callback?: () => void): void
Disables listening for the hide event of this panel. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | -------- |
| type | string | Yes| Listening type.<br>The value **'hide'** indicates the hide event.|
| callback | () => void | No | Callback used to return the result.|
**Example**
```js
panel.off('hide');
```
### changeFlag<sup>10+</sup> ### changeFlag<sup>10+</sup>
changeFlag(flag: PanelFlag): void changeFlag(flag: PanelFlag): void
...@@ -2487,7 +2582,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e ...@@ -2487,7 +2582,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------------------ | | -------- | ------------------------------ |
| 12800003 | Input method client error. | | 12800003 | input method client error. |
| 12800006 | Input method controller error. | | 12800006 | Input method controller error. |
**Example** **Example**
...@@ -2523,7 +2618,7 @@ Describes the attribute of a key. ...@@ -2523,7 +2618,7 @@ Describes the attribute of a key.
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------ | | --------- | -------- | ---- | ---- | ------------ |
| keyCode | number | Yes | No | Key value. For detail, see [KeyCode](js-apis-keycode.md#keycode).| | keyCode | number | Yes | No | Key value. For details, see [KeyCode](js-apis-keycode.md#keycode).|
| keyAction | number | Yes | No | Key event type.<br>- **2**: keydown event.<br>- **3**: keyup event.| | keyAction | number | Yes | No | Key event type.<br>- **2**: keydown event.<br>- **3**: keyup event.|
## PanelFlag<sup>10+</sup> ## PanelFlag<sup>10+</sup>
......
...@@ -94,6 +94,7 @@ Uploads files. This API uses a promise to return the result. You can use [on('co ...@@ -94,6 +94,7 @@ Uploads files. This API uses a promise to return the result. You can use [on('co
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.| | Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Error codes** **Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message| | ID| Error Message|
...@@ -104,6 +105,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ...@@ -104,6 +105,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
```js ```js
let uploadTask; let uploadTask;
let context;
let uploadConfig = { let uploadConfig = {
url: 'http://patch', url: 'http://patch',
header: { key1: "value1", key2: "value2" }, header: { key1: "value1", key2: "value2" },
...@@ -112,16 +114,20 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ...@@ -112,16 +114,20 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
data: [{ name: "name123", value: "123" }], data: [{ name: "name123", value: "123" }],
}; };
try { try {
request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { request.uploadFile(context, uploadConfig).then((data) => {
uploadTask = data; uploadTask = data;
}).catch((err) => { }).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error('err.code : ' + err.code + ', err.message : ' + err.message); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.uploadFile<sup>9+</sup> ## request.uploadFile<sup>9+</sup>
...@@ -142,6 +148,7 @@ Uploads files. This API uses an asynchronous callback to return the result. You ...@@ -142,6 +148,7 @@ Uploads files. This API uses an asynchronous callback to return the result. You
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.| | callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Error codes** **Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message| | ID| Error Message|
...@@ -152,6 +159,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ...@@ -152,6 +159,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
```js ```js
let uploadTask; let uploadTask;
let context;
let uploadConfig = { let uploadConfig = {
url: 'http://patch', url: 'http://patch',
header: { key1: "value1", key2: "value2" }, header: { key1: "value1", key2: "value2" },
...@@ -160,18 +168,22 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ...@@ -160,18 +168,22 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
data: [{ name: "name123", value: "123" }], data: [{ name: "name123", value: "123" }],
}; };
try { try {
request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { request.uploadFile(context, uploadConfig, (err, data) => {
if (err) { if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
uploadTask = data; uploadTask = data;
}); });
} catch (err) { } catch (err) {
console.error('err.code : ' + err.code + ', err.message : ' + err.message); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.upload<sup>(deprecated)</sup> ## request.upload<sup>(deprecated)</sup>
upload(config: UploadConfig): Promise&lt;UploadTask&gt; upload(config: UploadConfig): Promise&lt;UploadTask&gt;
...@@ -214,7 +226,7 @@ Uploads files. This API uses a promise to return the result. ...@@ -214,7 +226,7 @@ Uploads files. This API uses a promise to return the result.
request.upload(uploadConfig).then((data) => { request.upload(uploadConfig).then((data) => {
uploadTask = data; uploadTask = data;
}).catch((err) => { }).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
}) })
``` ```
...@@ -255,7 +267,7 @@ Uploads files. This API uses an asynchronous callback to return the result. ...@@ -255,7 +267,7 @@ Uploads files. This API uses an asynchronous callback to return the result.
}; };
request.upload(uploadConfig, (err, data) => { request.upload(uploadConfig, (err, data) => {
if (err) { if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
uploadTask = data; uploadTask = data;
...@@ -392,7 +404,7 @@ Unsubscribes from upload progress events. This API uses a callback to return the ...@@ -392,7 +404,7 @@ Unsubscribes from upload progress events. This API uses a callback to return the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).|
| callback | function | No| Callback used to return the result.<br>**uploadedSize**: size of the uploaded files, in bytes.<br>**totalSize**: Total size of the files to upload, in bytes. | | callback | function | No| Callback used to return the result.<br>**uploadedSize**: size of the uploaded files, in B.<br>**totalSize**: Total size of the files to upload, in B.|
**Example** **Example**
...@@ -487,12 +499,12 @@ Deletes this upload task. This API uses a promise to return the result. ...@@ -487,12 +499,12 @@ Deletes this upload task. This API uses a promise to return the result.
```js ```js
uploadTask.delete().then((result) => { uploadTask.delete().then((result) => {
if (result) { if (result) {
console.info('Upload task removed successfully. '); console.info('Succeeded in deleting the upload task.');
} else { } else {
console.error('Failed to remove the upload task. '); console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -518,13 +530,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r ...@@ -518,13 +530,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
```js ```js
uploadTask.delete((err, result) => { uploadTask.delete((err, result) => {
if (err) { if (err) {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Upload task removed successfully.'); console.info('Succeeded in deleting the upload task.');
} else { } else {
console.error('Failed to remove the upload task.'); console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -555,12 +567,12 @@ Removes this upload task. This API uses a promise to return the result. ...@@ -555,12 +567,12 @@ Removes this upload task. This API uses a promise to return the result.
```js ```js
uploadTask.remove().then((result) => { uploadTask.remove().then((result) => {
if (result) { if (result) {
console.info('Upload task removed successfully. '); console.info('Succeeded in removing the upload task.');
} else { } else {
console.error('Failed to remove the upload task. '); console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -590,13 +602,13 @@ Removes this upload task. This API uses an asynchronous callback to return the r ...@@ -590,13 +602,13 @@ Removes this upload task. This API uses an asynchronous callback to return the r
```js ```js
uploadTask.remove((err, result) => { uploadTask.remove((err, result) => {
if (err) { if (err) {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Upload task removed successfully.'); console.info('Succeeded in removing the upload task.');
} else { } else {
console.error('Failed to remove the upload task.'); console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -640,7 +652,7 @@ Describes the list of files in [UploadConfig](#uploadconfig). ...@@ -640,7 +652,7 @@ Describes the list of files in [UploadConfig](#uploadconfig).
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| filename | string | Yes| File name in the header when **multipart** is used.| | filename | string | Yes| File name in the header when **multipart** is used.|
| name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.|
| uri | string | Yes| Local path for storing files.<br>Only the **internal** protocol type is supported. In the value, **internal://cache/** is mandatory. Example:<br>internal://cache/path/to/file.txt | | uri | string | Yes| Local path for storing files.<br>Only the **internal** protocol type is supported. In the value, **"internal://cache/"** must be included. Example:<br>internal://cache/path/to/file.txt |
| type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.|
...@@ -681,29 +693,35 @@ Downloads files. This API uses a promise to return the result. You can use [on(' ...@@ -681,29 +693,35 @@ Downloads files. This API uses a promise to return the result. You can use [on('
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.| | Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Error codes** **Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 13400001 | file operation error. | | 13400001 | file operation error. |
| 13400002 | bad file path. | | 13400002 | bad file path. |
| 13400003 | task manager service error. | | 13400003 | task service ability error. |
**Example** **Example**
```js ```js
let downloadTask; let downloadTask;
let context;
try { try {
request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data; downloadTask = data;
}).catch((err) => { }).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
}) })
} catch (err) { } catch (err) {
console.error('err.code : ' + err.code + ', err.message : ' + err.message); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.downloadFile<sup>9+</sup> ## request.downloadFile<sup>9+</sup>
...@@ -725,32 +743,38 @@ Downloads files. This API uses an asynchronous callback to return the result. Yo ...@@ -725,32 +743,38 @@ Downloads files. This API uses an asynchronous callback to return the result. Yo
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Error codes** **Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 13400001 | file operation error. | | 13400001 | file operation error. |
| 13400002 | bad file path. | | 13400002 | bad file path. |
| 13400003 | task manager service error. | | 13400003 | task service ability error. |
**Example** **Example**
```js ```js
let downloadTask; let downloadTask;
let context;
try { try {
request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', request.downloadFile(context, { url: 'https://xxxx/xxxxx.hap',
filePath: 'xxx/xxxxx.hap'}, (err, data) => { filePath: 'xxx/xxxxx.hap'}, (err, data) => {
if (err) { if (err) {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
downloadTask = data; downloadTask = data;
}); });
} catch (err) { } catch (err) {
console.error('err.code : ' + err.code + ', err.message : ' + err.message); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.download<sup>(deprecated)</sup> ## request.download<sup>(deprecated)</sup>
download(config: DownloadConfig): Promise&lt;DownloadTask&gt; download(config: DownloadConfig): Promise&lt;DownloadTask&gt;
...@@ -786,7 +810,7 @@ Downloads files. This API uses a promise to return the result. ...@@ -786,7 +810,7 @@ Downloads files. This API uses a promise to return the result.
request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data; downloadTask = data;
}).catch((err) => { }).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
}) })
``` ```
...@@ -821,7 +845,7 @@ Downloads files. This API uses an asynchronous callback to return the result. ...@@ -821,7 +845,7 @@ Downloads files. This API uses an asynchronous callback to return the result.
request.download({ url: 'https://xxxx/xxxxx.hap', request.download({ url: 'https://xxxx/xxxxx.hap',
filePath: 'xxx/xxxxx.hap'}, (err, data) => { filePath: 'xxx/xxxxx.hap'}, (err, data) => {
if (err) { if (err) {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
downloadTask = data; downloadTask = data;
...@@ -898,7 +922,7 @@ Unsubscribes from download progress events. This API uses a callback to return t ...@@ -898,7 +922,7 @@ Unsubscribes from download progress events. This API uses a callback to return t
on(type: 'complete'|'pause'|'remove', callback:() =&gt; void): void on(type: 'complete'|'pause'|'remove', callback:() =&gt; void): void
Subscribes to download events. This API uses a callback to return the result synchronously. Subscribes to download events. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -995,7 +1019,7 @@ Subscribes to download failure events. This API uses a callback to return the re ...@@ -995,7 +1019,7 @@ Subscribes to download failure events. This API uses a callback to return the re
```js ```js
let failCallback = (err) => { let failCallback = (err) => {
console.info('Download task failed. Cause:' + err); console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`);
}; };
downloadTask.on('fail', failCallback); downloadTask.on('fail', failCallback);
``` ```
...@@ -1022,7 +1046,7 @@ Unsubscribes from download failure events. This API uses a callback to return th ...@@ -1022,7 +1046,7 @@ Unsubscribes from download failure events. This API uses a callback to return th
```js ```js
let failCallback = (err) => { let failCallback = (err) => {
console.info(`Download delete fail notification. err: ${err.message}`); console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`);
}; };
downloadTask.off('fail', failCallback); downloadTask.off('fail', failCallback);
``` ```
...@@ -1048,12 +1072,12 @@ Removes this download task. This API uses a promise to return the result. ...@@ -1048,12 +1072,12 @@ Removes this download task. This API uses a promise to return the result.
```js ```js
downloadTask.delete().then((result) => { downloadTask.delete().then((result) => {
if (result) { if (result) {
console.info('Download task removed.'); console.info('Succeeded in removing the download task.');
} else { } else {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch ((err) => { }).catch ((err) => {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1079,13 +1103,13 @@ Deletes this download task. This API uses an asynchronous callback to return the ...@@ -1079,13 +1103,13 @@ Deletes this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.delete((err, result)=>{ downloadTask.delete((err, result)=>{
if(err) { if(err) {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task removed.'); console.info('Succeeded in removing the download task.');
} else { } else {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -1111,9 +1135,9 @@ Obtains the information about this download task. This API uses a promise to ret ...@@ -1111,9 +1135,9 @@ Obtains the information about this download task. This API uses a promise to ret
```js ```js
downloadTask.getTaskInfo().then((downloadInfo) => { downloadTask.getTaskInfo().then((downloadInfo) => {
console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) console.info('Succeeded in querying the download task')
}) .catch((err) => { }) .catch((err) => {
console.error('Failed to query the download task. Cause:' + err) console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
}); });
``` ```
...@@ -1139,9 +1163,9 @@ Obtains the information about this download task. This API uses an asynchronous ...@@ -1139,9 +1163,9 @@ Obtains the information about this download task. This API uses an asynchronous
```js ```js
downloadTask.getTaskInfo((err, downloadInfo)=>{ downloadTask.getTaskInfo((err, downloadInfo)=>{
if(err) { if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
} else { } else {
console.info('download query success. data:'+ JSON.stringify(downloadInfo)); console.info('Succeeded in querying the download mimeType');
} }
}); });
``` ```
...@@ -1167,9 +1191,9 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur ...@@ -1167,9 +1191,9 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur
```js ```js
downloadTask.getTaskMimeType().then((data) => { downloadTask.getTaskMimeType().then((data) => {
console.info('Download task queried. Data:' + JSON.stringify(data)); console.info('Succeeded in querying the download MimeType');
}).catch((err) => { }).catch((err) => {
console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
}); });
``` ```
...@@ -1195,9 +1219,9 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca ...@@ -1195,9 +1219,9 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca
```js ```js
downloadTask.getTaskMimeType((err, data)=>{ downloadTask.getTaskMimeType((err, data)=>{
if(err) { if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
} else { } else {
console.info('Download task queried. data:' + JSON.stringify(data)); console.info('Succeeded in querying the download mimeType');
} }
}); });
``` ```
...@@ -1224,12 +1248,12 @@ Pauses this download task. This API uses a promise to return the result. ...@@ -1224,12 +1248,12 @@ Pauses this download task. This API uses a promise to return the result.
```js ```js
downloadTask.suspend().then((result) => { downloadTask.suspend().then((result) => {
if (result) { if (result) {
console.info('Download task paused. '); console.info('Succeeded in pausing the download task.');
} else { } else {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1255,13 +1279,13 @@ Pauses this download task. This API uses an asynchronous callback to return the ...@@ -1255,13 +1279,13 @@ Pauses this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.suspend((err, result)=>{ downloadTask.suspend((err, result)=>{
if(err) { if(err) {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task paused. '); console.info('Succeeded in pausing the download task.');
} else { } else {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -1288,13 +1312,13 @@ Resumes this download task. This API uses a promise to return the result. ...@@ -1288,13 +1312,13 @@ Resumes this download task. This API uses a promise to return the result.
```js ```js
downloadTask.restore().then((result) => { downloadTask.restore().then((result) => {
if (result) { if (result) {
console.info('Download task resumed.') console.info('Succeeded in resuming the download task.')
} else { } else {
console.error('Failed to resume the download task. '); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
} }
console.info('Download task resumed.') console.info('Succeeded in resuming the download task.')
}).catch((err) => { }).catch((err) => {
console.error('Failed to resume the download task. Cause:' + err); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1320,19 +1344,18 @@ Resumes this download task. This API uses an asynchronous callback to return the ...@@ -1320,19 +1344,18 @@ Resumes this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.restore((err, result)=>{ downloadTask.restore((err, result)=>{
if (err) { if (err) {
console.error('Failed to resume the download task. Cause:' + err); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task resumed.'); console.info('Succeeded in resuming the download task.');
} else { } else {
console.error('Failed to resume the download task.'); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
### remove<sup>(deprecated)</sup> ### remove<sup>(deprecated)</sup>
remove(): Promise&lt;boolean&gt; remove(): Promise&lt;boolean&gt;
...@@ -1358,12 +1381,12 @@ Removes this download task. This API uses a promise to return the result. ...@@ -1358,12 +1381,12 @@ Removes this download task. This API uses a promise to return the result.
```js ```js
downloadTask.remove().then((result) => { downloadTask.remove().then((result) => {
if (result) { if (result) {
console.info('Download task removed.'); console.info('Succeeded in removing the download task.');
} else { } else {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch ((err) => { }).catch ((err) => {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1386,20 +1409,20 @@ Removes this download task. This API uses an asynchronous callback to return the ...@@ -1386,20 +1409,20 @@ Removes this download task. This API uses an asynchronous callback to return the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result. | | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task deletion result.|
**Example** **Example**
```js ```js
downloadTask.remove((err, result)=>{ downloadTask.remove((err, result)=>{
if(err) { if(err) {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task removed.'); console.info('Succeeded in removing the download task.');
} else { } else {
console.error('Failed to remove the download task.'); console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -1429,9 +1452,9 @@ Queries this download task. This API uses a promise to return the result. ...@@ -1429,9 +1452,9 @@ Queries this download task. This API uses a promise to return the result.
```js ```js
downloadTask.query().then((downloadInfo) => { downloadTask.query().then((downloadInfo) => {
console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) console.info('Succeeded in querying the download task.')
}) .catch((err) => { }) .catch((err) => {
console.error('Failed to query the download task. Cause:' + err) console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
}); });
``` ```
...@@ -1461,9 +1484,9 @@ Queries this download task. This API uses an asynchronous callback to return the ...@@ -1461,9 +1484,9 @@ Queries this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.query((err, downloadInfo)=>{ downloadTask.query((err, downloadInfo)=>{
if(err) { if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
} else { } else {
console.info('download query success. data:'+ JSON.stringify(downloadInfo)); console.info('Succeeded in querying the download task.');
} }
}); });
``` ```
...@@ -1493,9 +1516,9 @@ Queries the **MimeType** of this download task. This API uses a promise to retur ...@@ -1493,9 +1516,9 @@ Queries the **MimeType** of this download task. This API uses a promise to retur
```js ```js
downloadTask.queryMimeType().then((data) => { downloadTask.queryMimeType().then((data) => {
console.info('Download task queried. Data:' + JSON.stringify(data)); console.info('Succeededto in querying the download MimeType.');
}).catch((err) => { }).catch((err) => {
console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
}); });
``` ```
...@@ -1525,9 +1548,9 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca ...@@ -1525,9 +1548,9 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca
```js ```js
downloadTask.queryMimeType((err, data)=>{ downloadTask.queryMimeType((err, data)=>{
if(err) { if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
} else { } else {
console.info('Download task queried. data:' + JSON.stringify(data)); console.info('Succeeded in querying the download mimeType.');
} }
}); });
``` ```
...@@ -1558,12 +1581,12 @@ Pauses this download task. This API uses a promise to return the result. ...@@ -1558,12 +1581,12 @@ Pauses this download task. This API uses a promise to return the result.
```js ```js
downloadTask.pause().then((result) => { downloadTask.pause().then((result) => {
if (result) { if (result) {
console.info('Download task paused. '); console.info('Succeeded in pausing the download task.');
} else { } else {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1593,13 +1616,13 @@ Pauses this download task. This API uses an asynchronous callback to return the ...@@ -1593,13 +1616,13 @@ Pauses this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.pause((err, result)=>{ downloadTask.pause((err, result)=>{
if(err) { if(err) {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task paused. '); console.info('Succeeded in pausing the download task.');
} else { } else {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -1630,13 +1653,13 @@ Resumes this download task. This API uses a promise to return the result. ...@@ -1630,13 +1653,13 @@ Resumes this download task. This API uses a promise to return the result.
```js ```js
downloadTask.resume().then((result) => { downloadTask.resume().then((result) => {
if (result) { if (result) {
console.info('Download task resumed.') console.info('Succeeded in resuming the download task.')
} else { } else {
console.error('Failed to resume the download task. '); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
} }
console.info('Download task resumed.') console.info('Succeeded in resuming the download task.')
}).catch((err) => { }).catch((err) => {
console.error('Failed to resume the download task. Cause:' + err); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -1666,13 +1689,13 @@ Resumes this download task. This API uses an asynchronous callback to return the ...@@ -1666,13 +1689,13 @@ Resumes this download task. This API uses an asynchronous callback to return the
```js ```js
downloadTask.resume((err, result)=>{ downloadTask.resume((err, result)=>{
if (err) { if (err) {
console.error('Failed to resume the download task. Cause:' + err); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
return; return;
} }
if (result) { if (result) {
console.info('Download task resumed.'); console.info('Succeeded in resuming the download task.');
} else { } else {
console.error('Failed to resume the download task.'); console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
} }
}); });
``` ```
...@@ -1693,7 +1716,7 @@ Defines the download task configuration. ...@@ -1693,7 +1716,7 @@ Defines the download task configuration.
| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.<br>- **true**: allowed<br>- **false**: not allowed| | enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.<br>- **true**: allowed<br>- **false**: not allowed|
| description | string | No| Description of the download session.| | description | string | No| Description of the download session.|
| filePath<sup>7+</sup> | string | No| Path where the downloaded file is stored.<br>- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.<br>- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| | filePath<sup>7+</sup> | string | No| Path where the downloaded file is stored.<br>- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.<br>- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.|
| networkType | number | No| Network type allowed for download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.<br>- NETWORK_MOBILE: 0x00000001<br>- NETWORK_WIFI: 0x00010000| | networkType | number | No| Network type allowed for the download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.<br>- NETWORK_MOBILE: 0x00000001<br>- NETWORK_WIFI: 0x00010000|
| title | string | No| Download task name.| | title | string | No| Download task name.|
| background<sup>9+</sup> | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| | background<sup>9+</sup> | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.|
...@@ -1706,7 +1729,7 @@ Defines the download task information, which is the callback parameter of the [g ...@@ -1706,7 +1729,7 @@ Defines the download task information, which is the callback parameter of the [g
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
| Name| Type|Mandatory| Description| | Name| Type|Mandatory| Description|
| -------- | ------ |---------------- | | -------- | -------- | -------- | -------- |
| downloadId | number |Yes| ID of the download task.| | downloadId | number |Yes| ID of the download task.|
| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| | failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).|
| fileName | string |Yes| Name of the downloaded file.| | fileName | string |Yes| Name of the downloaded file.|
...@@ -1718,4 +1741,1373 @@ Defines the download task information, which is the callback parameter of the [g ...@@ -1718,4 +1741,1373 @@ Defines the download task information, which is the callback parameter of the [g
| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| | downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.|
| description | string |Yes| Description of the download task.| | description | string |Yes| Description of the download task.|
| downloadedBytes | number |Yes| Size of the files downloaded, in bytes.| | downloadedBytes | number |Yes| Size of the files downloaded, in bytes.|
## Action<sup>10+</sup>
Defines action options.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Value|Description|
| -------- | -------- |-------- |
| DOWNLOAD | 0 |Download.|
| UPLOAD | 1 |Upload.|
## Mode<sup>10+</sup>
Defines mode options.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Value|Description|
| -------- | -------- |-------- |
| BACKGROUND | 0 |Background task.|
| FOREGROUND | 1 |Foreground task.|
## Network<sup>10+</sup>
Defines network options.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Value|Description|
| -------- | -------- |-------- |
| ANY | 0 |Network of any type.|
| WIFI | 1 |Wi-Fi network.|
| CELLULAR | 2 |Cellular data network.|
## FileSpec<sup>10+</sup>
Provides the file information of a table item.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| File path. The options are as follows:<br>- Relative path in the cache folder of the invoker.<br>- URI (applicable when the application has the permission to access the URI).|
| mimeType | string | No| MIME type of the file. The default value is as follows:<br>- During an upload, the value is obtained from the file name or URI suffix.<br>- During a download, the value is **Content-Type** when there is response and **octet-stream** otherwise.|
| filename | string | No| File name. The default value is obtained from the file path.|
| extras | Object | No| Additional information of the file.|
## FormItem<sup>10+</sup>
Describes the form item of a task.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Form parameter name.|
| value | string \| [FileSpec](#filespec10) \| Array&lt;[FileSpec](#filespec10)&gt; | Yes| Form parameter value.|
## Conf<sup>10+</sup>
Provides the configuration information of an upload or download task.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**|
| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.|
| title | string | No| Task title. The value contains a maximum of 256 characters. This parameter is left blank by default.|
| description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.|
| mode | [Mode](#mode10) | No| Task mode. The default mode is background.<br>- For a foreground task, a callback is used for notification.<br>- For a background task, the system notification and network connection features (detection, recovery, and automatic retry) are provided.|
| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.<br>- **true**: Overwrite the existing file.<br>- **false**: Do not overwrite the existing file. In this case, the download fails.|
| method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.<br>- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.<br>- If the task is a download, use **GET** or **POST**. The default value is **GET**.|
| headers | object | No| HTTPS headers to be included in the task.<br>- If the task is an upload, the default **Content-Type** is **multipart/form-data**.<br>- If the task is a download, the default **Content-Type** is **application/json**.|
| data | string \| Array&lt;[FormItem](#formitem10)&gt; | No| Task data.<br>- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.<br>- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null.|
| saveas | string | No| Path for storing downloaded files. The options are as follows:<br>- Relative path in the cache folder of the invoker, for example, ./xxx/yyy/zzz.html and xxx/yyy/zzz.html.<br>- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. Currently, this type is not supported.<br>The default value is a relative path in the cache folder of the application.|
| network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).|
| metered | boolean | No| Whether the task is allowed on a metered connection. The default value is **false**.|
| roaming | boolean | No| Whether the task is allowed on a roaming network. The default value is **true**.|
| retry | boolean | No| Whether automatic retry is enabled for background tasks. The default value is **true**.|
| redirect | boolean | No| Whether redirection is allowed. The default value is **true**.|
| index | number | No| Path index of the task. It is usually used for resumable downloads. The default value is **0**.|
| begins | number | No| File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the beginning of the upload.|
| ends | number | No| File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the end of the upload.|
| gauge | boolean | No| Whether to send progress notifications. This parameter applies only to background tasks. The default value is **false**.<br>- **false**: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.<br>- **true**: Progress notifications are sent to indicate the result of each file.|
| precise | boolean | No| - If this parameter is set to **true**, the task fails when the file size cannot be obtained.<br>- If this parameter is set to **false**, the task continues when the file size is set to **-1**.<br>The default value is **false**.|
| token | string | No| Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.|
| extras | object | No| Additional information of the task. This parameter is left blank by default.|
## State<sup>10+</sup>
Defines the current task status.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Value|Description|
| -------- | -------- |-------- |
| INITIALIZED | 0x00 |The task is initialized based on the configuration specified in [Conf](#conf10).|
| WAITING | 0x10 |The task lacks resources for running or the resources for retries do not match the network status.|
| RUNNING | 0x20 |The task is being executed.|
| RETRYING | 0x21 |The task has failed at least once and is being executed again.|
| PAUSED | 0x30 |The task is suspended and will be resumed later.|
| STOPPED | 0x31 |The task is stopped.|
| COMPLETED | 0x40 |The task is complete.|
| FAILED | 0x41 |The task fails.|
| REMOVED | 0x50 |The task is removed.|
## Progress<sup>10+</sup>
Describes the data structure of the task progress.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| state | [State](#state10) | Yes| Current task status.|
| index | number | Yes| Index of the file that is being processed in the task.|
| processed | number | Yes| Size of processed data in the current file in the task, in bytes.|
| sizes | Array&lt;number&gt; | Yes| Size of files in the task, in bytes.|
| extras | object | No| Extra information of the task, for example, the header and body of the response from the server.|
## Broken<sup>10+</sup>
Defines the cause of a task failure.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Value|Description|
| -------- | -------- |-------- |
| OTHERS | 0xFF |Other fault.|
| DISCONNECTED | 0x00 |Network disconnection.|
| TIMEOUT | 0x10 |Timeout.|
| PROTOCOL | 0x20 |Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416).|
| FSIO | 0x40 |File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation.|
## TaskInfo<sup>10+</sup>
Defines the data structure of the task information for query. The fields available varies depends on the query type.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uid | string | No| UID of the application. It is only available for query by system applications.<br>**System API**: This is a system API.|
| bundle | string | No| Bundle name of the application. It is only available for query by system applications.<br>**System API**: This is a system API.|
| url | string | No| Task URL. It is only available for query by non-system applications. An empty string is returned for query by system applications.|
| data | string \| Array&lt;[FormItem](#formitem10)&gt; | No| Task value.|
| tid | string | Yes| Task ID.|
| title | string | Yes| Task title.|
| description | string | Yes| Task description.|
| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**|
| mode | [Mode](#mode10) | Yes| Task mode.<br>- **FOREGROUND**<br>- **BACKGROUND**|
| mimeType | string | Yes| MIME type in the task configuration.|
| progress | [Progress](#progress10) | Yes| Task progress.|
| gauge | boolean | Yes| Whether to send progress notifications. This parameter applies only to background tasks.|
| ctime | string | Yes| Date and time when a task is created in UTC mode. The value is generated by the system of the current device.|
| mtime | string | Yes| Date and time when a task is modified in UTC mode. The value is generated by the system of the current device.|
| retry | boolean | Yes| Whether automatic retry is enabled for the task. This parameter applies only to background tasks.|
| tries | number | Yes| Number of retries of the task.|
| broken | [Broken](#broken10) | Yes| Failure cause of the task.<br>- **OTHERS**: other fault.<br>- **DISCONNECT**: network disconnection.<br>- **TIMEOUT**: timeout.<br>- **PROTOCOL**: protocol error.<br>- **FSIO**: file system I/O error.|
| reason | string | Yes| Reason why the task is waiting, failed, stopped, or paused.|
| extras | string | No| Extra information of the task|
## Task<sup>10+</sup>
Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create<sup>10+</sup>](#requestagentcreate10-1) or from a callback through [request.agent.create<sup>10+</sup>](#requestagentcreate10).
### Attributes
Task attributes include the task ID and task configuration.
**System capability**: SystemCapability.Request.FileTransferAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.|
| conf | [Conf](#conf10) | Yes| Task configuration.|
### on('progress')<sup>10+</sup>
on(event: 'progress', callback: (progress: Progress) =&gt; void): void
Subscribes to task progress events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.|
| callback | function | Yes| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOnTest",
value: {
filename: "taskOnTest.avi",
mimetype: "application/octet-stream",
path: "./taskOnTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOnTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOnCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('progress', createOnCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### on('completed')<sup>10+</sup>
on(event: 'completed', callback: (progress: Progress) =&gt; void): void
Subscribes to task completion events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.|
| callback | function | Yes| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOnTest",
value: {
filename: "taskOnTest.avi",
mimetype: "application/octet-stream",
path: "./taskOnTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOnTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOnCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('completed', createOnCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### on('failed')<sup>10+</sup>
on(event: 'failed', callback: (progress: Progress) =&gt; void): void
Subscribes to task failure events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.|
| callback | function | Yes| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOnTest",
value: {
filename: "taskOnTest.avi",
mimetype: "application/octet-stream",
path: "./taskOnTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOnTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOnCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('failed', createOnCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### off('progress')<sup>10+</sup>
off(event: 'progress', callback?: (progress: Progress) =&gt; void): void
Unsubscribes from task progress events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.|
| callback | function | No| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOffTest",
value: {
filename: "taskOffTest.avi",
mimetype: "application/octet-stream",
path: "./taskOffTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOffTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOffCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('progress', createOffCallback);
task.off('progress', createOffCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### off('completed')<sup>10+</sup>
off(event: 'completed', callback?: (progress: Progress) =&gt; void): void
Unsubscribes from task completion events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.|
| callback | function | No| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOffTest",
value: {
filename: "taskOffTest.avi",
mimetype: "application/octet-stream",
path: "./taskOffTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOffTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOffCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('completed', createOffCallback);
task.off('completed', createOffCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### off('failed')<sup>10+</sup>
off(event: 'failed', callback?: (progress: Progress) =&gt; void): void
Unsubscribes from task failure events.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.|
| callback | function | No| Callback used to return the data structure of the task progress.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "taskOffTest",
value: {
filename: "taskOffTest.avi",
mimetype: "application/octet-stream",
path: "./taskOffTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'taskOffTest',
description: 'Sample code for event listening',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
let createOffCallback = (progress) => {
console.info('upload task completed.');
};
request.agent.create(context, conf).then((task)=> {
task.on('failed', createOffCallback);
task.off('failed', createOffCallback);
console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### start<sup>10+</sup>
start(callback: AsyncCallback&lt;void&gt;): void
Starts this task. This API cannot be used to start an initialized task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskStartTest',
description: 'Sample code for start the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.start((err) => {
if (err) {
console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in starting a download task.`);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### start<sup>10+</sup>
start(): Promise&lt;void&gt;
Starts this task. This API cannot be used to start an initialized task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskStartTest',
description: 'Sample code for start the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.start().then(() => {
console.info(`Succeeded in starting a download task.`);
}).catch((err) => {
console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
### pause<sup>10+</sup>
pause(callback: AsyncCallback&lt;void&gt;): void
Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900005 | task mode error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskPauseTest',
description: 'Sample code for pause the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.pause((err) => {
if (err) {
console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in pausing a download task. `);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
### pause<sup>10+</sup>
pause(): Promise&lt;void&gt;
Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses a promise to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900005 | task mode error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskPauseTest',
description: 'Sample code for pause the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.pause().then(() => {
console.info(`Succeeded in pausing a download task. `);
}).catch((err) => {
console.error(`Failed to pause the upload task, Code: ${err.code}, message: ${err.message}`);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});
```
### resume<sup>10+</sup>
resume(callback: AsyncCallback&lt;void&gt;): void
Resumes this task. This API can be used to resume a paused background task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900005 | task mode error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskResumeTest',
description: 'Sample code for resume the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.resume((err) => {
if (err) {
console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in resuming a download task. `);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
### resume<sup>10+</sup>
resume(): Promise&lt;void&gt;
Resumes this task. This API can be used to resume a paused background task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900005 | task mode error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskResumeTest',
description: 'Sample code for resume the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.resume().then(() => {
console.info(`Succeeded in resuming a download task. `);
}).catch((err) => {
console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
### stop<sup>10+</sup>
stop(callback: AsyncCallback&lt;void&gt;): void
Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskStopTest',
description: 'Sample code for stop the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.stop((err) => {
if (err) {
console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in stopping a download task. `);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
### stop<sup>10+</sup>
stop(): Promise&lt;void&gt;
Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900007 | task state error. |
**Example**
```js
let context;
let conf = {
action: request.agent.Action.DOWNLOAD,
url: 'http://127.0.0.1',
title: 'taskStopTest',
description: 'Sample code for stop the download task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "GET",
data: "",
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task) => {
task.stop().then(() => {
console.info(`Succeeded in stopping a download task. `);
}).catch((err) => {
console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
});
console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
## request.agent.create<sup>10+</sup>
create(context: BaseContext, conf: Conf, callback: AsyncCallback&lt;Task&gt;): void
Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 tasks, and a maximum of 300 tasks can be carried. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| conf | [Conf](#conf10) | Yes| Task configuration.|
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| callback | AsyncCallback&lt;[Task](#task10)&gt; | Yes| Callback used to return the configuration about the created task.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | file operation error. |
| 13400003 | task service ability error. |
| 21900004 | application task queue full error. |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "reeateTest",
value: {
filename: "reeateTest.avi",
mimetype: "application/octet-stream",
path: "./reeateTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'reeateTest',
description: 'Sample code for reeate task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf, (err, task) => {
if (err) {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in creating a download task. result: ${task.conf}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.agent.create<sup>10+</sup>
create(context: BaseContext, conf: Conf): Promise&lt;Task&gt;
Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 tasks, and a maximum of 300 tasks can be carried. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| conf | [Conf](#conf10) | Yes| Task configuration.|
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;[Task](#task10)&gt; | Promise used to return the configuration about the created task.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | file operation error. |
| 13400003 | task service ability error. |
| 21900004 | application task queue full error. |
| 21900005 | task mode error. |
**Example**
```js
let context;
let attachments = [{
name: "reeateTest",
value: {
filename: "reeateTest.avi",
mimetype: "application/octet-stream",
path: "./reeateTest.avi",
}
}];
let conf = {
action: request.agent.Action.UPLOAD,
url: 'http://127.0.0.1',
title: 'reeateTest',
description: 'Sample code for reeate task',
mode: request.agent.Mode.BACKGROUND,
overwrite: false,
method: "PUT",
data: attachments,
saveas: "./",
network: request.agent.Network.CELLULAR,
metered: false,
roaming: true,
retry: true,
redirect: true,
index: 0,
begins: 0,
ends: -1,
gauge: false,
precise: false,
token: "it is a secret"
};
request.agent.create(context, conf).then((task)=> {
console.info(`Succeeded in creating a download task. result: ${task.conf}`);
}).catch((err) => {
console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});
```
> **NOTE**
>
> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## request.agent.remove<sup>10+</sup>
remove(id: string, callback: AsyncCallback&lt;void&gt;): void
Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| id | string | Yes| Task ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900006 | task not found error. |
**Example**
```js
request.agent.remove("id", (err) => {
if (err) {
console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in creating a download task.`);
});
```
## request.agent.remove<sup>10+</sup>
remove(id: string): Promise&lt;void&gt;
Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result.
**System capability**: SystemCapability.Request.FileTransferAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| id | string | Yes| Task ID.|
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400003 | task service ability error. |
| 21900006 | task not found error. |
**Example**
```js
request.agent.remove("id").then(() => {
console.info(`Succeeded in removing a download task. `);
}).catch((err) => {
console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`);
});
```
<!--no_check--> <!--no_check-->
...@@ -3515,7 +3515,7 @@ struct WebComponent { ...@@ -3515,7 +3515,7 @@ struct WebComponent {
pageUp(top:boolean): void pageUp(top:boolean): void
Scrolls the page up by half the view port or jumps to the top of the page. Scrolls the page up by half the viewport or jumps to the top of the page.
**System capability**: SystemCapability.Web.Webview.Core **System capability**: SystemCapability.Web.Webview.Core
...@@ -3523,7 +3523,7 @@ Scrolls the page up by half the view port or jumps to the top of the page. ...@@ -3523,7 +3523,7 @@ Scrolls the page up by half the view port or jumps to the top of the page.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the view port.| | top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the viewport.|
**Error codes** **Error codes**
...@@ -3564,7 +3564,7 @@ struct WebComponent { ...@@ -3564,7 +3564,7 @@ struct WebComponent {
pageDown(bottom:boolean): void pageDown(bottom:boolean): void
Scrolls the page down by half the view port or jumps to the bottom of the page. Scrolls the page down by half the viewport or jumps to the bottom of the page.
**System capability**: SystemCapability.Web.Webview.Core **System capability**: SystemCapability.Web.Webview.Core
...@@ -3572,7 +3572,7 @@ Scrolls the page down by half the view port or jumps to the bottom of the page. ...@@ -3572,7 +3572,7 @@ Scrolls the page down by half the view port or jumps to the bottom of the page.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the view port.| | bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the viewport.|
**Error codes** **Error codes**
......
...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | View port of the shape.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.| | viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | Viewport of the shape.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
......
...@@ -34,7 +34,7 @@ This error code is reported when a file path error occurs in invoking the **uplo ...@@ -34,7 +34,7 @@ This error code is reported when a file path error occurs in invoking the **uplo
**Possible Causes** **Possible Causes**
The file path is incorrect or the file aready exists in the path. The file path is incorrect or the file already exists in the path.
**Solution** **Solution**
...@@ -44,7 +44,7 @@ Verify the file path. ...@@ -44,7 +44,7 @@ Verify the file path.
**Error Message** **Error Message**
Task manager service error. Task service ability error.
**Description** **Description**
...@@ -57,3 +57,96 @@ The task fails to be created. ...@@ -57,3 +57,96 @@ The task fails to be created.
**Solution** **Solution**
Verify the task settings. Verify the task settings.
## 21900004 Application Task Queue Full
**Error Message**
application task queue full error.
**Description**
This error code is reported when the application task queue is full.
**Possible Causes**
The application fails to create a background task (resources are preempted by foreground tasks, where no task queue is involved).
**Solution**
1. Obtain all background tasks of the application through the query API.
2. Proactively remove tasks not needed to release the quota.
3. Create a background task again.
## 21900005 Task Mode Error
**Error Message**
task mode error.
**Description**
This error code is reported when a task mode error occurs.
**Possible Causes**
The application attempts to create a foreground task when it is not running in the foreground.
**Solution**
1. Register and deregister an event listener for a foreground application.
2. Follow the instructions in the API reference document.
## 21900006 Task Not Found
**Error Message**
task not found error.
**Description**
This error code is reported when the task is not found.
**Possible Causes**
The task to remove or query does not exist.
**Solution**
1. Query existing tasks through the query API.
2. Check whether the target task exists. (The system periodically deletes junk tasks.)
3. Verify the task ID and try again.
## 21900007 Operation Not Supported in Current State
**Error Message**
task mode error.
**Description**
This error code is reported when the operation performed is not supported.
**Possible Causes**
1. The task to start has been deleted.
2. The task to start has not been initialized.
3. The task to pause is not being executed.
4. The task to resume is not paused.
5. The task to stop is not being executed.
**Solution**
1. Check the task status.
2. Perform the operation supported by the current task status.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册