提交 b7436e24 编写于 作者: J jiangminyang

Merge branch 'master' of https://gitee.com/jiang-minyang/docs

...@@ -200,7 +200,7 @@ zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang ...@@ -200,7 +200,7 @@ zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
## When to Use ## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group. With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported. The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs ## Available APIs
...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState'; ...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.| | function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. | | function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**.| | function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
...@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState'; ...@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState';
..., ...,
"reqPermissions": [ "reqPermissions": [
{ {
"name": "ohos.permission.BUNDLE_ACTIVE_INFO" "name": "ohos.permission.BUNDLE_ACTIVE_INFO"
} }
] ]
} }
...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState'; ...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => { stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState'; ...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => { stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1; let i = 1;
for (let key in res){ for (let key in res){
...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState'; ...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
}); });
...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState'; ...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState'; ...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
}); });
...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState'; ...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Callback mode // Callback mode
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState'; ...@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState';
} }
}); });
``` ```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself. 7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself.
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.isIdleState("com.ohos.camera").then( res => { stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
}); });
...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState'; ...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.getRecentlyUsedModules(1000).then( res => { stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i]));
} }
}).catch( err=> { }).catch(err=> {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
}); });
// Promise mode when maxNum is not specified // Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => { stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState'; ...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => { stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState'; ...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified // Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => { stats.getRecentlyUsedModules((err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState'; ...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppNotificationNumber(0, 20000000000000).then( res => { stats.queryAppNotificationNumber(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
}); });
...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState'; ...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveEventStates(0, 20000000000000).then( res => { stats.queryBundleActiveEventStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => {
if (err) { if (err) {
...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState'; ...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode without parameters // Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode without parameters // Asynchronous callback mode without parameters
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState'; ...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
// Promise mode with parameters // Promise mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName).then( res => { stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode with parameters // Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState'; ...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => { stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => { stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState'; ...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState'; ...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged).then( () => { stats.registerGroupCallBack(onBundleGroupChanged).then(() => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
...@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState'; ...@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{ stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
} }
}); });
``` ```
13. Deregister the callback for application group changes. 13. Deregister the callback for application group changes.
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
//promise //promise
stats.unRegisterGroupCallBack().then( () => { stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
}); });
//callback //callback
stats.unRegisterGroupCallBack((err)=>{ stats.unRegisterGroupCallBack((err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
## When to Use ## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc. The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs ## Available APIs
...@@ -36,13 +36,29 @@ The following table describes APIs available for mutual conversion between coord ...@@ -36,13 +36,29 @@ The following table describes APIs available for mutual conversion between coord
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
``` ```
2. Obtain the conversion result. 2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information. - Call **getAddressesFromLocation** to convert coordinates into geographical location information.
``` ```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => { geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data)); if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
}); });
``` ```
...@@ -51,8 +67,12 @@ The following table describes APIs available for mutual conversion between coord ...@@ -51,8 +67,12 @@ The following table describes APIs available for mutual conversion between coord
``` ```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => { geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data)); if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
}); });
``` ```
......
...@@ -123,7 +123,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -123,7 +123,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
The following example instantiates the **RequestParam** object for navigation: The following example instantiates the **RequestParam** object for navigation:
``` ```
var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
**Method 2:** **Method 2:**
...@@ -152,7 +152,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -152,7 +152,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
The following example instantiates the **RequestParam** object for the location accuracy priority policy: The following example instantiates the **RequestParam** object for the location accuracy priority policy:
``` ```
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
4. Instantiate the **Callback** object for the system to report location results. 4. Instantiate the **Callback** object for the system to report location results.
...@@ -179,8 +179,12 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -179,8 +179,12 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application does not need the real-time device location, it can use the last known device location cached in the system instead. If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
``` ```
geolocation.getLastLocation((data) => { geolocation.getLastLocation((err, data) => {
console.log('getLastLocation: data: ' + JSON.stringify(data)); if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
}); });
``` ```
......
# Using Native APIs in Application Projects # Using Native APIs in Application Projects
OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the **arkui_napi** repository are used to implement the interaction with JS. Currently, the **arkui_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository.
## How to Develop ## How to Develop
The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **arkui_napi** repository for development. The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability. You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability.
...@@ -74,7 +74,7 @@ export default storage; ...@@ -74,7 +74,7 @@ export default storage;
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_storage/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info) ...@@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info)
napi_create_async_work( napi_create_async_work(
env, nullptr, resource, env, nullptr, resource,
// Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using theNAPI because the execution is asynchronous. // Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using the NAPI because the execution is asynchronous.
[](napi_env env, void* data) { [](napi_env env, void* data) {
StorageAsyncContext* asyncContext = (StorageAsyncContext*)data; StorageAsyncContext* asyncContext = (StorageAsyncContext*)data;
auto itr = gKeyValueStorage.find(asyncContext->key); auto itr = gKeyValueStorage.find(asyncContext->key);
...@@ -307,7 +307,7 @@ export class NetServer { ...@@ -307,7 +307,7 @@ export class NetServer {
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_netserver/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp ...@@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_callback/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context) ...@@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context)
uv_queue_work( uv_queue_work(
loop, loop,
work, work,
// This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, the callback does not need to execute any task. // This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, this callback does not need to execute any task.
[](uv_work_t* work) {}, [](uv_work_t* work) {},
// This callback is executed in the JS thread bound to env. // This callback is executed in the JS thread bound to env.
[](uv_work_t* work, int status) { [](uv_work_t* work, int status) {
......
# APIs # APIs
- [API Reference Document Description](development-intro.md)
- Ability Framework - Ability Framework
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
...@@ -13,6 +15,7 @@ ...@@ -13,6 +15,7 @@
- [@ohos.application.appManager](js-apis-appmanager.md) - [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md) - [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
- [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md)
- [@ohos.ability.featureAbility](js-apis-featureAbility.md) - [@ohos.ability.featureAbility](js-apis-featureAbility.md)
- [@ohos.application.formBindingData](js-apis-formbindingdata.md) - [@ohos.application.formBindingData](js-apis-formbindingdata.md)
- [@ohos.application.FormExtension](js-apis-formextension.md) - [@ohos.application.FormExtension](js-apis-formextension.md)
...@@ -47,7 +50,7 @@ ...@@ -47,7 +50,7 @@
- application/[ServiceExtensionContext](js-apis-service-extension-context.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- application/[MissionInfo](js-apis-application-missionInfo.md) - application/[MissionInfo](js-apis-application-missionInfo.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.commonEvent](js-apis-commonEvent.md)
...@@ -55,7 +58,7 @@ ...@@ -55,7 +58,7 @@
- [@ohos.notification](js-apis-notification.md) - [@ohos.notification](js-apis-notification.md)
- [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md)
- application/[EventHub](js-apis-eventhub.md) - application/[EventHub](js-apis-eventhub.md)
- Bundle Management - Bundle Management
- [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle](js-apis-Bundle.md)
...@@ -70,14 +73,14 @@ ...@@ -70,14 +73,14 @@
- bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)
- bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[Metadata](js-apis-bundle-Metadata.md)
- bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md)
- UI Page - UI Page
- [@ohos.animator](js-apis-animator.md) - [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.prompt](js-apis-prompt.md) - [@ohos.prompt](js-apis-prompt.md)
- [@ohos.router](js-apis-router.md) - [@ohos.router](js-apis-router.md)
- Graphics - Graphics
- [@ohos.display ](js-apis-display.md) - [@ohos.display ](js-apis-display.md)
...@@ -85,7 +88,7 @@ ...@@ -85,7 +88,7 @@
- [@ohos.window](js-apis-window.md) - [@ohos.window](js-apis-window.md)
- [webgl](js-apis-webgl.md) - [webgl](js-apis-webgl.md)
- [webgl2](js-apis-webgl2.md) - [webgl2](js-apis-webgl2.md)
- Media - Media
- [@ohos.multimedia.audio](js-apis-audio.md) - [@ohos.multimedia.audio](js-apis-audio.md)
...@@ -93,41 +96,45 @@ ...@@ -93,41 +96,45 @@
- [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.image](js-apis-image.md)
- [@ohos.multimedia.media](js-apis-media.md) - [@ohos.multimedia.media](js-apis-media.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- Resource Management - Resource Management
- [@ohos.i18n](js-apis-i18n.md) - [@ohos.i18n](js-apis-i18n.md)
- [@ohos.intl](js-apis-intl.md) - [@ohos.intl](js-apis-intl.md)
- [@ohos.resourceManager](js-apis-resource-manager.md) - [@ohos.resourceManager](js-apis-resource-manager.md)
- Resource Scheduling - Resource Scheduling
- [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md)
- [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.workScheduler ](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
- Custom Management - Custom Management
- [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Security - Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.security.huks ](js-apis-huks.md) - [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- [@system.cipher](js-apis-system-cipher.md) - [@system.cipher](js-apis-system-cipher.md)
- Data Management - Data Management
- [@ohos.data.dataAbility ](js-apis-data-ability.md) - [@ohos.data.dataAbility ](js-apis-data-ability.md)
- [@ohos.data.dataShare](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.settings](js-apis-settings.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb/[resultSet](js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.document](js-apis-document.md) - [@ohos.document](js-apis-document.md)
...@@ -138,7 +145,7 @@ ...@@ -138,7 +145,7 @@
- [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md)
- [@ohos.volumeManager](js-apis-volumemanager.md) - [@ohos.volumeManager](js-apis-volumemanager.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- Telephony Service - Telephony Service
- [@ohos.contact](js-apis-contact.md) - [@ohos.contact](js-apis-contact.md)
...@@ -148,14 +155,15 @@ ...@@ -148,14 +155,15 @@
- [@ohos.telephony.sim](js-apis-sim.md) - [@ohos.telephony.sim](js-apis-sim.md)
- [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.sms](js-apis-sms.md)
- [@ohos.telephony.data](js-apis-telephony-data.md) - [@ohos.telephony.data](js-apis-telephony-data.md)
- Network Management - Network Management
- [@ohos.net.connection](js-apis-net-connection.md) - [@ohos.net.connection](js-apis-net-connection.md)
- [@ohos.net.http](js-apis-http.md) - [@ohos.net.http](js-apis-http.md)
- [@ohos.request](js-apis-request.md) - [@ohos.request](js-apis-request.md)
- [@ohos.net.socket](js-apis-socket.md) - [@ohos.net.socket](js-apis-socket.md)
- [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.bluetooth](js-apis-bluetooth.md)
...@@ -166,7 +174,7 @@ ...@@ -166,7 +174,7 @@
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
...@@ -185,7 +193,7 @@ ...@@ -185,7 +193,7 @@
- [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.wallpaper](js-apis-wallpaper.md) - [@ohos.wallpaper](js-apis-wallpaper.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- Device Management - Device Management
- [@ohos.batteryInfo ](js-apis-battery-info.md) - [@ohos.batteryInfo ](js-apis-battery-info.md)
...@@ -205,18 +213,19 @@ ...@@ -205,18 +213,19 @@
- [@ohos.power](js-apis-power.md) - [@ohos.power](js-apis-power.md)
- [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md) - [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.systemParameter](js-apis-system-parameter.md)
- [@ohos.thermal](js-apis-thermal.md) - [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md) - [@ohos.update](js-apis-update.md)
- [@ohos.usb](js-apis-usb.md) - [@ohos.usb](js-apis-usb.md)
- [@ohos.vibrator](js-apis-vibrator.md) - [@ohos.vibrator](js-apis-vibrator.md)
- Account Management - Account Management
- [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.appAccount](js-apis-appAccount.md)
- [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.distributedAccount](js-apis-distributed-account.md)
- [@ohos.account.osAccount](js-apis-osAccount.md) - [@ohos.account.osAccount](js-apis-osAccount.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.convertxml](js-apis-convertxml.md)
...@@ -240,11 +249,12 @@ ...@@ -240,11 +249,12 @@
- [@ohos.util.Vector](js-apis-vector.md) - [@ohos.util.Vector](js-apis-vector.md)
- [@ohos.worker](js-apis-worker.md) - [@ohos.worker](js-apis-worker.md)
- [@ohos.xml](js-apis-xml.md) - [@ohos.xml](js-apis-xml.md)
- Test - Test
- [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md) - [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained - APIs No Longer Maintained
- [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.bytrace](js-apis-bytrace.md)
......
# API Reference Document Description
API references provide the description of APIs used for application development. This topic describes common fields in the API references to help you better use the reference document.
## Version Description
In API references, the earliest versions of APIs and components are specified in the following ways:
- For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7."
- For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid<sup>8+</sup>" indicates that the **uid** attribute is supported since API version 8.
## Ability Framework Model Description
Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md).
- If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model."
- If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model."
- If both models are supported, no special description is provided.
## Available APIs
Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications.
A description regarding system APIs will be provided in the document.
- If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs."
- If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API."
## Permission Description
By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md).
To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Access Control Development](../../security/accesstoken-guidelines.md).
- If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx"
- If an application can call an API without any permission, no special description is provided.
To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md).
## System Capability Description
System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md).
The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx"
## Sample Code Language Description
OpenHarmony supports two development languages: JS and TS.
- When a code block is labeled with `js`, the sample code can be used in the JS and eTS projects.
- When a code block is labeled with `ts`, the sample code can be used only in the eTS project.
# AbilityManager
The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are system APIs and cannot be called by third-party applications.
# Modules to Import
```js
import AbilityManager from '@ohos.application.abilityManager'
```
## AbilityState
Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
| FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the foregrounding state. |
| BACKGROUNDING | 12 | The ability is in the backgrounding state. |
## updateConfiguration
updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
```
## updateConfiguration
updateConfiguration(config: Configuration): Promise\<void>
Updates the configuration. This API uses a promise to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<void> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
})
```
## getAbilityRunningInfos
getAbilityRunningInfos(callback: AsyncCallback\<Array\<AbilityRunningInfo>>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getAbilityRunningInfos
getAbilityRunningInfos(): Promise\<Array\<AbilityRunningInfo>>
Obtains the ability running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
Obtains the extension running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
})
```
## getTopAbility<sup>9+</sup>
getTopAbility(callback: AsyncCallback\<ElementName>): void;
Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<ElementName> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
});
```
## getTopAbility<sup>9+</sup>
getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<ElementName>| Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
})
```
...@@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance. ...@@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ------------ | | ----------------- | ------------ |
...@@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con ...@@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con
| name | string | Yes | Name of the app account to add. | | name | string | Yes | Name of the app account to add. |
| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| | extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
...@@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p ...@@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p
| ---- | ------ | ---- | ----------- | | ---- | ------ | ---- | ----------- |
| name | string | Yes | Name of the app account to delete.| | name | string | Yes | Name of the app account to delete.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A ...@@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use ...@@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app.| | bundleName | string | Yes | Bundle name of the app.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p ...@@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :-------------------- | | :--------------------- | :-------------------- |
...@@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu ...@@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu
| credentialType | string | Yes | Type of the credential to set.| | credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential to set. | | credential | string | Yes | Credential to set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur ...@@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| extraInfo | string | Yes | Additional information to set.| | extraInfo | string | Yes | Additional information to set.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use ...@@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| isEnable | boolean | Yes | Whether to enable app data synchronization.| | isEnable | boolean | Yes | Whether to enable app data synchronization.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur ...@@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur
| key | string | Yes | Key of the data to set. The private key can be customized.| | key | string | Yes | Key of the data to set. The private key can be customized.|
| value | string | Yes | Value of the data to be set. | | value | string | Yes | Value of the data to be set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the ...@@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to obtain.| | credentialType | string | Yes | Type of the credential to obtain.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
...@@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret ...@@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
...@@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t ...@@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to obtain.| | key | string | Yes | Key of the data to obtain.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
......
# Data Share Extension Ability
**DataShareExtensionAbility** provides extension abilities for data share services based on the ExtensionAbility framework.
>**NOTE**
>
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>The APIs provided by this module are system APIs.
>
>The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility'
```
## onCreate
onCreate?(want: Want, callback: AsyncCallback&lt;void&gt;): void
Called to initialize service logic of the server when the DataShare client connects to the DataShareExtensionAbility server. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
**Example**
```ts
import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want: Want, callback: AsyncCallback<void>) {
rdb.getRdbStore(this.context, {
name: DB_NAME
}, 1, function (err, data) {
console.log('getRdbStore done, data : ' + data);
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('executeSql done, error message : ' + err);
});
if (callback) {
callback();
}
});
}
};
```
## getFileTypes
getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Called by the server to obtain the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------------- | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME types to match. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the MIME types obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>) {
let err = {"code":0};
let ret = new Array("type01", "type02", "type03");
callback(err, ret);
}
};
```
## openFile
openFile?(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void
Called by the server to open a file. This method can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------------------------ |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | File open mode, including read-only mode and read/write mode.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the file descriptor. |
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
openFile(uri: string, mode: string, callback: AsyncCallback<number>) {
let err = {"code":0};
let fd = 0;
callback(err,fd);
}
};
```
## insert
insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
Called to insert data into the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri |string | Yes | URI of the data to insert.|
| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.|
| callback |AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the index of the data inserted.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
insert(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>) {
if (value == null) {
console.info('invalid valueBuckets');
return;
}
rdbStore.insert(TBL_NAME, value, function (err, ret) {
console.info('callback ret:' + ret);
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## update
update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
Called by the server to update data in the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to update.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.|
| valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of updated data records.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.update(TBL_NAME, value, predicates, function (err, ret) {
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## delete
delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void
Called by the server to delete data from the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- |
| uri | string | Yes | URI of the data to delete. |
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of data records deleted.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.delete(TBL_NAME, predicates, function (err, ret) {
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## query
query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void
Called by the server to query data from the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to query.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.|
| columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is empty, all columns will be queried.|
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback invoked to return the result set.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
if (resultSet != undefined) {
console.info('resultSet.rowCount: ' + resultSet.rowCount);
}
if (callback != undefined) {
callback(err, resultSet);
}
});
}
};
```
## getType
getType?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to obtain the MIME type corresponding to the given URI. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the target data.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the MIME type obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getType(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "image";
callback(err, ret);
}
};
```
## BatchInsert
BatchInsert?(uri: string, valueBuckets: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;): void
Called by the server to insert batch data into the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------- |
| uri | string | Yes | URI of the data to insert. |
| valueBuckets | Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes | Data to insert. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of inserted data records.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
batchInsert(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>) {
if (valueBuckets == null || valueBuckets.length == undefined) {
console.info('invalid valueBuckets');
return;
}
let resultNum = valueBuckets.length
valueBuckets.forEach(vb => {
rdbStore.insert(TBL_NAME, vb, function (err, ret) {
if (callback != undefined) {
callback(err, resultNum);
}
});
});
}
};
```
## normalizeUri
normalizeUri?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to normalize the specified URI. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ----------------------- |
| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. If the operation is successful, the normalized URI is returned. Otherwise, **null** is returned.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
normalizeUri(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "normalize+" + uri;
callback(err, ret);
}
};
```
## denormalizeUri
denormalizeUri?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to denormalize the specified URI. This method can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ----------------------- |
| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. If the operation is successful, the URI obtained is returned. If the URI passed in is returned, denormalization is not required. If denormalization is not supported, **null** is returned.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
denormalizeUri(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "denormalize+" + uri;
callback(err, ret);
}
};
```
# MissionInfo
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import MissionInfo from '@ohos.application.missionInfo'
```
## MissionInfo
Provides the mission information.
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| missionId | number | Yes| Yes| Mission ID.|
| runningState | number | Yes| Yes| Running state of the mission.|
| lockedState | boolean | Yes| Yes| Locked state of the mission.|
| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.|
| want | [Want](js-apis-application-Want.md) | Yes| Yes| **Want** information of the mission.|
| label | string | Yes| Yes| Label of the mission.|
| iconPath | string | Yes| Yes| Path of the mission icon.|
| continuable | boolean | Yes| Yes| Whether the mission is continuable.|
# DefaultAppManager
The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import defaultAppMgr from '@ohos.bundle.defaultAppManager'
```
## defaultAppMgr.ApplicationType
Enumerates the application types.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Description |
| -------- | -------- | -------------------------------------- |
| BROWSER | string | Default browser. |
| IMAGE | string | Default image viewer. |
| AUDIO | string | Default audio player. |
| VIDEO | string | Default video player. |
| PDF | string | Default PDF reader. |
| WORD | string | Default Word viewer. |
| EXCEL | string | Default Excel viewer. |
| PPT | string | Default PowerPoint viewer. |
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string): Promise\<boolean>
Checks whether this application is the default application of a system-defined application type. This API uses a promise to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<boolean> | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string, callback: AsyncCallback\<boolean>): void
Checks whether this application is the default application of a system-defined application type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------------------- | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId?: number): Promise\<BundleInfo>
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application.|
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.getDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId: number, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application of a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\<void>
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId: number, callback: AsyncCallback\<void>) : void;
Sets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCallback\<void>) : void;
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId?: number): Promise\<void>
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.resetDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\<void>) : void;
Resets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, callback: AsyncCallback\<void>) : void;
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
# Data Share Result Set
The **DataShareResultSet** module provides methods for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type.
>**NOTE**
>
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import DataShareResultSet from '@ohos.data.DataShareResultSet';
```
## How to Use
You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShareResultSet** object.
```ts
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let dataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
if (err != undefined) {
console.info("createDataShareHelper fail, error message : " + err);
} else {
console.info("createDataShareHelper end, data : " + data);
dataShareHelper = data;
}
});
let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates();
let resultSet;
da.equalTo("name", "ZhangSan");
dataShareHelper.query(uri, da, columns).then((data) => {
console.log("query end, data : " + data);
resultSet = data;
}).catch((err) => {
console.log("query fail, error message : " + err);
});
```
## Attributes
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Type | Mandatory| Description |
| ----------- | ------------- | ---- | ------------------------ |
| columnNames | Array&lt;string&gt; | Yes | Names of all columns in the result set. |
| columnCount | number | Yes | Number of columns in the result set. |
| rowCount | number | Yes | Number of rows in the result set. |
| isClosed | boolean | Yes | Whether the result set is closed.|
## goToFirstRow
goToFirstRow(): boolean
Moves to the first row of the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| :------ | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoTOFirstRow = resultSet.goToFirstRow();
console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow);
```
## goToLastRow
goToLastRow(): boolean
Moves to the last row of the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToLastRow = resultSet.goToLastRow();
console.info('resultSet.goToLastRow: ' + isGoToLastRow);
```
## goToNextRow
goToNextRow(): boolean
Moves to the next row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToNextRow = resultSet.goToNextRow();
console.info('resultSet.goToNextRow: ' + isGoToNextRow);
```
## goToPreviousRow
goToPreviousRow(): boolean
Moves to the previous row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToPreviousRow = resultSet.goToPreviousRow();
console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow);
```
## goTo
goTo(offset:number): boolean
Moves based on the specified offset.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | ------------------------------------------------------------ |
| offset | number | Yes | Offset relative to the current position. A negative value means to move backward, and a positive value means to move forward.|
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let goToNum = 1;
let isGoTo = resultSet.goTo(goToNum);
console.info('resultSet.goTo: ' + isGoTo);
```
## goToRow
goToRow(position: number): boolean
Moves to the specified row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | ------------------------ |
| position | number | Yes | Destination position to move.|
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let goToRowNum = 2
let isGoToRow = resultSet.goToRow(goToRowNum);
console.info('resultSet.goToRow: ' + isGoToRow);
```
## getBlob
getBlob(columnIndex: number): Uint8Array
Obtains the value in the specified column in the current row as a byte array.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ---------- | -------------------------------- |
| Uint8Array | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getBlob = resultSet.getBlob(columnIndex);
console.info('resultSet.getBlob: ' + getBlob);
```
## getString
getString(columnIndex: number): *string*
Obtains the value in the specified column in the current row as a string.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| string | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getString = resultSet.getString(columnIndex);
console.info('resultSet.getString: ' + getString);
```
## getLong
getLong(columnIndex: number): number
Obtains the value in the specified column in the current row as a long integer.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | -------------------------- |
| number | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getLong = resultSet.getLong(columnIndex);
console.info('resultSet.getLong: ' + getLong);
```
## getDouble
getDouble(columnIndex: number): number
Obtains the value in the specified column in the current row as a double-precision floating-point number.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| number | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getDouble = resultSet.getDouble(columnIndex);
console.info('resultSet.getDouble: ' + getDouble);
```
## close
close(): void
Closes this result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Example**
```ts
resultSet.close();
```
## getColumnIndex
getColumnIndex(columnName: string): number
Obtains the column index based on the column name.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | -------------------------- |
| columnName | string | Yes | Column name.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Column index obtained.|
**Example**
```ts
let ColumnName = "name"
let getColumnIndex = resultSet.getColumnIndex(ColumnName)
console.info('resultSet.getColumnIndex: ' + getColumnIndex);
```
## getColumnName
getColumnName(columnIndex: number): *string*
Obtains the column name based on the column index.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | -------------------------- |
| columnIndex | number | Yes | Column index.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| string | Column name obtained.|
**Example**
```ts
let columnIndex = 1
let getColumnName = resultSet.getColumnName(columnIndex)
console.info('resultSet.getColumnName: ' + getColumnName);
```
## getDataType
getDataType(columnIndex: number): DataType
Obtains the data type based on the specified column index.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | -------------------------- |
| columnIndex | number | Yes | Column index.|
**Return value**
| Type | Description |
| --------------------- | ------------------ |
| [DataType](#datatype) | Data type obtained.|
**Example**
```ts
let columnIndex = 1;
let getDataType = resultSet.getDataType(columnIndex);
console.info('resultSet.getDataType: ' + getDataType);
```
## DataType
Enumerates the data types.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Value| Description |
| ----------- | ------ | -------------------- |
| TYPE_NULL | 0 | Null. |
| TYPE_LONG | 1 | Long integer. |
| TYPE_DOUBLE | 2 | Double-precision floating-point number.|
| TYPE_STRING | 3 | String.|
| TYPE_BLOB | 4 | Byte array.|
# Value Bucket
The **ValueBucket** holds data in key-value (KV) pairs. You can use it to insert data into a database.
>**Note**
>
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import { ValueType } from '@ohos.data.ValuesBucket';
import { ValuesBucket } from '@ohos.data.ValuesBucket';
```
## ValueType
Enumerates the value types allowed by the database.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Description |
| ------- | -------------------- |
| number | The value is a number. |
| string | The value is a string.|
| boolean | The value is of Boolean type.|
## ValuesBucket
Holds a set of KV pairs.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Type | Mandatory| Description |
| ------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes | KV pairs in a **ValuesBucket**. The key is of the string type. The value can be a number, string, Boolean value, Unit8Array, or **null**.|
...@@ -489,7 +489,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) ...@@ -489,7 +489,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore)
let kvManager; let kvManager;
try { try {
console.log('GetAllKVStoreId'); console.log('GetAllKVStoreId');
kvManager.getAllKVStoreId('apppId').then((data) => { kvManager.getAllKVStoreId('appId').then((data) => {
console.log('getAllKVStoreId success'); console.log('getAllKVStoreId success');
console.log('size = ' + data.length); console.log('size = ' + data.length);
}).catch((err) => { }).catch((err) => {
...@@ -775,7 +775,7 @@ let kvStore; ...@@ -775,7 +775,7 @@ let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeeed.'); console.log('getResultSet succeeded.');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.log('getResultSet failed: ' + err);
...@@ -2453,10 +2453,10 @@ try { ...@@ -2453,10 +2453,10 @@ try {
console.log('entries: ' + JSON.stringify(entries)); console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key', function (err,entrys) { kvStore.getEntries('batch_test_string_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -2505,7 +2505,7 @@ try { ...@@ -2505,7 +2505,7 @@ try {
console.log('entries: ' + JSON.stringify(entries)); console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entrys) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('PutBatch ' + JSON.stringify(entries)); console.log('PutBatch ' + JSON.stringify(entries));
}).catch((err) => { }).catch((err) => {
...@@ -3245,10 +3245,10 @@ try { ...@@ -3245,10 +3245,10 @@ try {
} }
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_number_key', function (err,entrys) { kvStore.getEntries('batch_test_number_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -3297,12 +3297,12 @@ try { ...@@ -3297,12 +3297,12 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entrys) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
console.log('entrys[0].value.value: ' + entrys[0].value.value); console.log('entries[0].value.value: ' + entries[0].value.value);
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
}); });
...@@ -3353,10 +3353,10 @@ try { ...@@ -3353,10 +3353,10 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query, function (err,entrys) { kvStore.getEntries(query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -3409,7 +3409,7 @@ try { ...@@ -3409,7 +3409,7 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entrys) => { kvStore.getEntries(query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
...@@ -3650,7 +3650,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** ...@@ -3650,7 +3650,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates**
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | | predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| | callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
**Example** **Example**
...@@ -4134,7 +4134,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail ...@@ -4134,7 +4134,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
| query |[Query](#querysup8sup) | Yes |**Query** object to match. | | query |[Query](#query8) | Yes |**Query** object to match. |
| delayMs |number | No |Allowed synchronization delay time, in ms. | | delayMs |number | No |Allowed synchronization delay time, in ms. |
**Example** **Example**
...@@ -4252,7 +4252,7 @@ try { ...@@ -4252,7 +4252,7 @@ try {
console.log('getSecurityLevel success'); console.log('getSecurityLevel success');
}); });
}catch(e) { }catch(e) {
console.log('GetSecurityLeve e ' + e); console.log('GetSecurityLevel e ' + e);
} }
``` ```
...@@ -4282,7 +4282,7 @@ try { ...@@ -4282,7 +4282,7 @@ try {
console.log('getSecurityLevel fail ' + JSON.stringify(err)); console.log('getSecurityLevel fail ' + JSON.stringify(err));
}); });
}catch(e) { }catch(e) {
console.log('GetSecurityLeve e ' + e); console.log('GetSecurityLevel e ' + e);
} }
``` ```
...@@ -4412,10 +4412,10 @@ try { ...@@ -4412,10 +4412,10 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -4465,12 +4465,12 @@ try { ...@@ -4465,12 +4465,12 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
console.log('entrys[0].value.value: ' + entrys[0].value.value); console.log('entries[0].value.value: ' + entries[0].value.value);
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
}); });
...@@ -4522,10 +4522,10 @@ try { ...@@ -4522,10 +4522,10 @@ try {
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
kvStore.getEntries(query, function (err,entrys) { kvStore.getEntries(query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -4578,7 +4578,7 @@ try { ...@@ -4578,7 +4578,7 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entrys) => { kvStore.getEntries(query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
...@@ -4633,10 +4633,10 @@ try { ...@@ -4633,10 +4633,10 @@ try {
var query = new distributedData.Query(); var query = new distributedData.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query, function (err,entrys) { kvStore.getEntries('localDeviceId', query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}) })
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -4691,7 +4691,7 @@ try { ...@@ -4691,7 +4691,7 @@ try {
var query = new distributedData.Query(); var query = new distributedData.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query).then((entrys) => { kvStore.getEntries('localDeviceId', query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
......
...@@ -14,21 +14,21 @@ import document from '@ohos.document'; ...@@ -14,21 +14,21 @@ import document from '@ohos.document';
choose(types? : string[]): Promise&lt;string&gt; choose(types? : string[]): Promise&lt;string&gt;
Chooses a file of the specified type using the file manager. This API uses a promise to return the result. Chooses files of the specified types using the file manager. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- | | ------ | ------ | ---- | ---------------------------- |
| types | string[] | No | Type of the file to choose.| | types | string[] | No | Types of the files to choose. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;string&gt; | Promise used to return the result. An error code is returned.| | Promise&lt;string&gt; | Promise used to return the result. An error code is returned.|
**Example** **Example**
...@@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to ...@@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example** **Example**
...@@ -62,16 +62,16 @@ Chooses a file using the file manager. This API uses an asynchronous callback to ...@@ -62,16 +62,16 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
choose(types:string[], callback:AsyncCallback&lt;string&gt;): void choose(types:string[], callback:AsyncCallback&lt;string&gt;): void
Chooses a file using the file manager. This API uses an asynchronous callback to return the result. Chooses files using the file manager. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| types | string[] | No | Type of the file to choose.| | types | string[] | No | Types of the files to choose.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example** **Example**
...@@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result. ...@@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- | | ---- | ------ | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.| | uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.| | type | string | Yes | Type of the file to open.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;void&gt; | Promise used to return the result. An error code is returned.| | Promise&lt;void&gt; | Promise used to return the result. An error code is returned.|
**Example** **Example**
...@@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result. ...@@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.| | uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.| | type | string | Yes | Type of the file to open.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. |
**Example** **Example**
......
...@@ -287,7 +287,7 @@ Defines the information about an input device. ...@@ -287,7 +287,7 @@ Defines the information about an input device.
| Name | Type | Description | | Name | Type | Description |
| -------- | ------------------------- | --------------------------------- | | -------- | ------------------------- | --------------------------------- |
| type | [ChangeType](#changetype) | Device change type, which indicates whether an input device is inserted or removed. | | type | [ChangedType](#changedtype) | Device change type, which indicates whether an input device is inserted or removed. |
| deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
## InputDeviceData ## InputDeviceData
......
# Privacy Management # Privacy Management
Provides APIs for privacy management, such as management of permission usage records. The **PrivacyManager** module provides APIs for privacy management, such as management of permission usage records.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications. > The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import ## Modules to Import
...@@ -19,7 +19,6 @@ import privacyManager from '@ohos.privacyManager'; ...@@ -19,7 +19,6 @@ import privacyManager from '@ohos.privacyManager';
addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise&lt;number&gt; addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise&lt;number&gt;
Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result.
The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application.
**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications)
...@@ -41,10 +40,6 @@ The permission usage record includes the application identity of the invoker, na ...@@ -41,10 +40,6 @@ The permission usage record includes the application identity of the invoker, na
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;number&gt; | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| | Promise&lt;number&gt; | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.|
```
```
**Example** **Example**
```js ```js
...@@ -59,7 +54,6 @@ privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED ...@@ -59,7 +54,6 @@ privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED
addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback&lt;number&gt;): void addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback&lt;number&gt;): void
Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result.
The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application.
**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications)
...@@ -202,7 +196,7 @@ Represents the permission usage records of all applications. ...@@ -202,7 +196,7 @@ Represents the permission usage records of all applications.
## BundleUsedRecord ## BundleUsedRecord
Represents the application access records of an application. Represents the permission access records of an application.
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -212,11 +206,11 @@ Represents the application access records of an application. ...@@ -212,11 +206,11 @@ Represents the application access records of an application.
| isRemote | boolean | No | Whether the token ID belongs to a remote device. The default value is **false**.| | isRemote | boolean | No | Whether the token ID belongs to a remote device. The default value is **false**.|
| deviceId | string | No | ID of the device hosting the target application. | | deviceId | string | No | ID of the device hosting the target application. |
| bundleName | string | No | Bundle name of the target application.| | bundleName | string | No | Bundle name of the target application.|
| permissionRecords | Array&lt;[PermissionUsedRecord](#PermissionUsedRecord)&gt; | No | Permission usage records of the specified application obtained. | | permissionRecords | Array&lt;[PermissionUsedRecord](#PermissionUsedRecord)&gt; | No | Permission usage records of the target application. |
## PermissionUsedRecord ## PermissionUsedRecord
Represents the access records of a permission. Represents the usage records of a permission.
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -225,8 +219,8 @@ Represents the access records of a permission. ...@@ -225,8 +219,8 @@ Represents the access records of a permission.
| permissionName | string | No | Name of the permission. | | permissionName | string | No | Name of the permission. |
| accessCount | number | No | Total number of times that the permission is accessed.| | accessCount | number | No | Total number of times that the permission is accessed.|
| rejectCount | number | No | Total number of times that the access to the permission is rejected.| | rejectCount | number | No | Total number of times that the access to the permission is rejected.|
| lastAccessTime | number | No | Last time when the permission was accessed, in ms.| | lastAccessTime | number | No | Last time when the permission was accessed, accurate to ms.|
| lastRejectTime | number | No | Last time when the access to the permission was rejected, in ms.| | lastRejectTime | number | No | Last time when the access to the permission was rejected, accurate to ms.|
| lastAccessDuration | number | No | Last access duration, in ms.| | lastAccessDuration | number | No | Last access duration, in ms.|
| accessRecords | Array&lt;[UsedRecordDetail](#usedrecorddetail)&gt; | No | Access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | | accessRecords | Array&lt;[UsedRecordDetail](#usedrecorddetail)&gt; | No | Access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. |
| rejectRecords | Array&lt;[UsedRecordDetail](#usedrecorddetail)&gt; | No | Rejected records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | | rejectRecords | Array&lt;[UsedRecordDetail](#usedrecorddetail)&gt; | No | Rejected records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. |
......
...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications.
```js ```js
var child = process.runCmd('ls'); var child = process.runCmd('ls');
var result = child.wait(); var result = child.wait();
child.getOutput.then(val=>{ child.getOutput().then(val=>{
console.log("child.getOutput = " + val); console.log("child.getOutput = " + val);
}) })
``` ```
...@@ -119,7 +119,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -119,7 +119,7 @@ This is a system API and cannot be called by third-party applications.
```js ```js
var child = process.runCmd('madir test.text'); var child = process.runCmd('madir test.text');
var result = child.wait(); var result = child.wait();
child.getErrorOutput.then(val=>{ child.getErrorOutput().then(val=>{
console.log("child.getErrorOutput= " + val); console.log("child.getErrorOutput= " + val);
}) })
``` ```
...@@ -286,7 +286,7 @@ Obtains the thread priority based on the specified TID. ...@@ -286,7 +286,7 @@ Obtains the thread priority based on the specified TID.
**Example** **Example**
```js ```js
var tid = process.getTid(); var tid = process.tid;
var pres = process.getThreadPriority(tid); var pres = process.getThreadPriority(tid);
``` ```
...@@ -617,5 +617,5 @@ Sends a signal to the specified process to terminate it. ...@@ -617,5 +617,5 @@ Sends a signal to the specified process to terminate it.
```js ```js
var pres = process.pid var pres = process.pid
var result = that.kill(28, pres) var result = process.kill(28, pres)
``` ```
...@@ -1141,7 +1141,7 @@ Obtains the string corresponding to the specified resource name. This API return ...@@ -1141,7 +1141,7 @@ Obtains the string corresponding to the specified resource name. This API return
resourceManager.getStringByNameSync("test"); resourceManager.getStringByNameSync("test");
``` ```
### getBoolean<sup>9+</sup> ### getBoolean<sup>9+</sup>
getBoolean(resId: number): boolean getBoolean(resId: number): boolean
...@@ -1187,7 +1187,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP ...@@ -1187,7 +1187,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
resourceManager.getBooleanByName("boolean_test"); resourceManager.getBooleanByName("boolean_test");
``` ```
### getNumber<sup>9+</sup> ### getNumber<sup>9+</sup>
getNumber(resId: number): number getNumber(resId: number): number
......
...@@ -3,13 +3,6 @@ ...@@ -3,13 +3,6 @@
## setTimeout ## setTimeout
## Modules to Import
```
import Time from '@ohos.Time';
```
setTimeout(handler[,delay[,…args]]): number setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off. Sets a timer for the system to call a function after the timer goes off.
......
...@@ -72,8 +72,8 @@ Obtains the query string applicable to this URI. ...@@ -72,8 +72,8 @@ Obtains the query string applicable to this URI.
**Example** **Example**
```js ```js
const uri = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const result = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
uri.toString() result.toString()
``` ```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册