首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

HarmonyOS Next开发学习手册——DataAbility组件

  • 25-02-22 06:41
  • 4640
  • 13016
blog.csdn.net

DataAbility,即"使用Data模板的Ability",主要用于对外部提供统一的数据访问抽象,不提供用户交互界面。DataAbility可由PageAbility、ServiceAbility或其他应用启动,即使用户切换到其他应用,DataAbility仍将在后台继续运行。

使用DataAbility有助于应用管理其自身和其他应用存储数据的访问,并提供与其他应用共享数据的方法。DataAbility既可用于同设备不同应用的数据共享,也支持跨设备不同应用的数据共享。

数据的存放形式多样,可以是数据库,也可以是磁盘上的文件。DataAbility对外提供对数据的增、删、改、查,以及打开文件等接口,这些接口的具体实现由开发者提供。

DataAbility组件配置

URI介绍

DataAbility的提供方和使用方都通过URI(Uniform Resource Identifier)来标识一个具体的数据,例如数据库中的某个表或磁盘上的某个文件。此处的URI仍基于URI通用标准,格式如下:

  • scheme:协议方案名,固定为"dataability",代表Data Ability所使用的协议类型。

  • authority:设备ID。如果为跨设备场景,则为目标设备的ID;如果为本地设备场景,则不需要填写。

  • path:资源的路径信息,代表特定资源的位置信息。

  • query:查询参数。

  • fragment:可以用于指示要访问的子资源。

URI示例:

  • 跨设备场景:dataability://device_id/com.domainname.dataability.persondata/person/10

  • 本地设备:dataability:///com.domainname.dataability.persondata/person/1

说明
本地设备的"device_id"字段为空,因此在"dataability:“后面有三个”/"。

部分配置项介绍

与PageAbility类似,DataAbility的相关配置在config.json配置文件的"module"对象的"abilities"对象中,与PageAbility的区别在于"type"属性及"uri"属性。

表1 DataAbility的部分配置项说明

Json重要字段备注说明
“name”Ability名称。
“type”UIAbility类型,DataAbility的类型为"data"。
“uri”通信使用的URI。
“visible”对其他应用是否可见,设置为true时,DataAbility才能与其他应用进行通信传输数据。

config.json配置样例

"abilities": [
  ...
  {
    "name": ".DataAbility",
    "srcLanguage": "ets",
    "srcPath": "DataAbility",
    "icon": "$media:icon",
    "description": "$string:DataAbility_desc",
    "type": "data",
    "visible": true,
    "uri": "dataability://com.samples.famodelabilitydevelop.DataAbility",
    "readPermission": "ohos.permission.READ_CONTACTS",
    "writePermission": "ohos.permission.WRITE_CONTACTS"
  },
  ...
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

DataAbility支持的配置项及详细说明详见 module对象内部结构 。

DataAbility的生命周期

应用开发者可以根据业务场景实现data.js/data.ets中的生命周期相关接口。DataAbility生命周期接口说明见下表。

表1 DataAbility相关生命周期API功能介绍

接口名描述
onInitialized?(info: AbilityInfo): void在Ability初始化调用,通过此回调方法执行RDB等初始化操作。
update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void更新数据库中的数据。
query?(uri: string, columns: Array, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void查询数据库中的数据。
delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void删除一条或多条数据。
normalizeUri?(uri: string, callback: AsyncCallback): void对URI进行规范化。一个规范化的URI可以支持跨设备使用、持久化、备份和还原等,当上下文改变时仍然可以引用到相同的数据项。
batchInsert?(uri: string, valueBuckets: Array, callback: AsyncCallback): void向数据库中插入多条数据。
denormalizeUri?(uri: string, callback: AsyncCallback): void将一个由normalizeUri生产的规范化URI转换成非规范化的URI。
insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback): void向数据中插入一条数据。
openFile?(uri: string, mode: string, callback: AsyncCallback): void打开一个文件。
getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback): void获取文件的MIME类型。
getType?(uri: string, callback: AsyncCallback): void获取URI指定数据相匹配的MIME类型。
executeBatch?(ops: Array, callback: AsyncCallback): void批量操作数据库中的数据。
call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback): void自定义方法。

创建DataAbility

实现DataAbility中Insert、Query、Update、Delete接口的业务内容。保证能够满足数据库存储业务的基本需求。BatchInsert与ExecuteBatch接口已经在系统中实现遍历逻辑,依赖Insert、Query、Update、Delete接口逻辑,来实现数据的批量处理。

创建DataAbility的代码示例如下:

import featureAbility from '@ohos.ability.featureAbility';
import type common from '@ohos.app.ability.common';
import type Want from '@ohos.app.ability.Want';
import type { AsyncCallback, BusinessError } from '@ohos.base';
import dataAbility from '@ohos.data.dataAbility';
import rdb from '@ohos.data.rdb';
import hilog from '@ohos.hilog';

let TABLE_NAME = 'book';
let STORE_CONFIG: rdb.StoreConfig = { name: 'book.db' };
let SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)';
let rdbStore: rdb.RdbStore | undefined = undefined;
const TAG: string = '[Sample_FAModelAbilityDevelop]';
const domain: number = 0xFF00;

class DataAbility {
  onInitialized(want: Want): void {
    hilog.info(domain, TAG, 'DataAbility onInitialized, abilityInfo:' + want.bundleName);
    let context: common.BaseContext = { stageMode: featureAbility.getContext().stageMode };
    rdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
      hilog.info(domain, TAG, 'DataAbility getRdbStore callback');
      store.executeSql(SQL_CREATE_TABLE, []);
      rdbStore = store;
    });
  }

  insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback): void {
    hilog.info(domain, TAG, 'DataAbility insert start');
    if (rdbStore) {
      rdbStore.insert(TABLE_NAME, valueBucket, callback);
    }
  }

  batchInsert(uri: string, valueBuckets: Array, callback: AsyncCallback): void {
    hilog.info(domain, TAG, 'DataAbility batch insert start');
    if (rdbStore) {
      for (let i = 0; i < valueBuckets.length; i++) {
        hilog.info(domain, TAG, 'DataAbility batch insert i=' + i);
        if (i < valueBuckets.length - 1) {
          rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: BusinessError, num: number) => {
            hilog.info(domain, TAG, 'DataAbility batch insert ret=' + num);
          });
        } else {
          rdbStore.insert(TABLE_NAME, valueBuckets[i], callback);
        }
      }
    }
  }

  query(uri: string, columns: Array, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void {
    hilog.info(domain, TAG, 'DataAbility query start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.query(rdbPredicates, columns, callback);
    }
  }

  update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void {
    hilog.info(domain, TAG, 'DataAbility update start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.update(valueBucket, rdbPredicates, callback);
    }
  }

  delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void {
    hilog.info(domain, TAG, 'DataAbility delete start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.delete(rdbPredicates, callback);
    }
  }
}

export default new DataAbility();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

启动DataAbility

启动DataAbility会获取一个工具接口类对象(DataAbilityHelper)。启动DataAbility的示例代码如下:

import featureAbility from '@ohos.ability.featureAbility';
import ability from '@ohos.ability.ability';

let uri: string = 'dataability:///com.samples.famodelabilitydevelop.DataAbility';
let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(uri);
  • 1
  • 2
  • 3
  • 4
  • 5

访问DataAbility

访问DataAbility需导入基础依赖包,以及获取与DataAbility子模块通信的URI字符串。

其中,基础依赖包包括:

  • @ohos.ability.featureAbility
  • @ohos.data.dataAbility
  • @ohos.data.relationalStore

访问DataAbility的示例代码如下:

  1. 创建工具接口类对象。
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
import relationalStore from '@ohos.data.relationalStore';
import ability from '@ohos.ability.ability';
// 作为参数传递的URI,与config中定义的URI的区别是多了一个"/",有三个"/"
let uri: string = 'dataability:///com.samples.famodelabilitydevelop.DataAbility';
let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(uri);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 构建数据库相关的RDB数据。
import ohos_data_ability from '@ohos.data.dataAbility';
import rdb from '@ohos.data.rdb';
let valuesBucket_insert: rdb.ValuesBucket = { name: 'Rose', introduction: 'insert' };
let valuesBucket_update: rdb.ValuesBucket = { name: 'Rose', introduction: 'update' };
let crowd = new Array({ name: 'Rose', introduction: 'batchInsert_one' } as rdb.ValuesBucket,
  { name: 'Rose', introduction: 'batchInsert_two' } as rdb.ValuesBucket);
let columnArray = new Array('id', 'name', 'introduction');
let predicates = new ohos_data_ability.DataAbilityPredicates();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注:关于DataAbilityPredicates的详细内容,请参考DataAbility谓词 。

  1. 调用insert方法向指定的DataAbility子模块插入数据。
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
this.DAHelper.insert(this.uri, this.valuesBucket_insert, (error: BusinessError, data: number) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'insert_failed_toast'
    });
  } else {
    promptAction.showToast({
   message: 'insert_success_toast'
    });
  }
  Logger.info(TAG, 'DAHelper insert result: ' + data + ', error: ' + JSON.stringify(error));
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

import featureAbility from '@ohos.ability.featureAbility'
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
this.DAHelper.insert(this.uri, this.valuesBucket_insert).then((datainsert) => {
  promptAction.showToast({
    message: 'insert_success_toast'
  });
  Logger.info(TAG, 'DAHelper insert result: ' + datainsert);
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'insert_success_toast'
  });
  Logger.error(TAG, `DAHelper insert failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  1. 调用delete方法删除DataAbility子模块中指定的数据。
import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
this.DAHelper.delete(this.uri, this.predicates, (error, data) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'delete_failed_toast'
    });
  } else {
    promptAction.showToast({
      message: 'delete_success_toast'
    });
 }
  Logger.info(TAG, 'DAHelper delete result: ' + data + ', error: ' + JSON.stringify(error));
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
this.DAHelper.delete(this.uri, this.predicates).then((datadelete) => {
 promptAction.showToast({
    message: 'delete_success_toast'
  });
  Logger.info(TAG, 'DAHelper delete result: ' + datadelete);
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'delete_failed_toast'
  });
  Logger.error(TAG, `DAHelper delete failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  1. 调用update方法更新指定DataAbility子模块中的数据。
import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
this.predicates.equalTo('name', 'Rose');
this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates, (error, data) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'update_failed_toast'
    });
  } else {
    promptAction.showToast({
      message: 'update_success_toast'
    });
 }
  Logger.info(TAG, 'DAHelper update result: ' + data + ', error: ' + JSON.stringify(error));
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
this.predicates.equalTo('name', 'Rose');
this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates).then((dataupdate) => {
 promptAction.showToast({
    message: 'update_success_toast'
  });
  Logger.info(TAG, 'DAHelper update result: ' + dataupdate);
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'update_failed_toast'
  });
  Logger.error(TAG, `DAHelper update failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  1. 调用query方法在指定的DataAbility子模块中查找数据。
import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
this.predicates.equalTo('name', 'Rose');
this.DAHelper.query(this.uri, this.columnArray, this.predicates, (error, data) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'query_failed_toast'
    });
    Logger.error(TAG, `DAHelper query failed. Cause: ${error.message}`);
  } else {
    promptAction.showToast({
      message: 'query_success_toast'
 });
  }
  // ResultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
  while (data.goToNextRow()) {
 const id = data.getLong(data.getColumnIndex('id'));
    const name = data.getString(data.getColumnIndex('name'));
    const introduction = data.getString(data.getColumnIndex('introduction'));
    Logger.info(TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`);
  }
  // 释放数据集的内存
  data.close();
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
this.predicates.equalTo('name', 'Rose');
this.DAHelper.query(this.uri, this.columnArray, this.predicates).then((dataquery) => {
  promptAction.showToast({
    message: 'query_success_toast'
  });
  // ResultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
  while (dataquery.goToNextRow()) {
    const id = dataquery.getLong(dataquery.getColumnIndex('id'));
    const name = dataquery.getString(dataquery.getColumnIndex('name'));
    const introduction = dataquery.getString(dataquery.getColumnIndex('introduction'));
    Logger.info(TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`);
  }
  // 释放数据集的内存
  dataquery.close();
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'query_failed_toast'
  });
  Logger.error(TAG, `DAHelper query failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  1. 调用batchInsert方法向指定的DataAbility子模块批量插入数据。
import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
this.DAHelper.batchInsert(this.uri, this.crowd, (error, data) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'batchInsert_failed_toast'
    });
  } else {
    promptAction.showToast({
      message: 'batchInsert_success_toast'
    });
 }
  Logger.info(TAG, 'DAHelper batchInsert result: ' + data + ', error: ' + JSON.stringify(error));
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
this.DAHelper.batchInsert(this.uri, this.crowd).then((databatchInsert) => {
 promptAction.showToast({
    message: 'batchInsert_success_toast'
  });
  Logger.info(TAG, 'DAHelper batchInsert result: ' + databatchInsert);
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'batchInsert_failed_toast'
  });
  Logger.error(TAG, `DAHelper batchInsert failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  1. 调用executeBatch方法向指定的DataAbility子模块进行数据的批量处理。
import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// callback方式调用:
let operations: Array = [{
  uri: this.uri,
  type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
  valuesBucket: { name: 'Rose', introduction: 'executeBatch' },
  predicates: this.predicates,
  expectedCount: 0,
  predicatesBackReferences: undefined,
  interrupted: true,
}];
this.DAHelper.executeBatch(this.uri, operations, (error, data) => {
  if (error && error.code !== 0) {
    promptAction.showToast({
      message: 'executeBatch_failed_toast'
    });
  } else {
    promptAction.showToast({
      message: 'executeBatch_success_toast'
    });
  }
 Logger.info(TAG, `DAHelper executeBatch, result: ` + JSON.stringify(data) + ', error: ' + JSON.stringify(error));
}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

import featureAbility from '@ohos.ability.featureAbility'
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PageDataAbility';

// promise方式调用(await需要在async方法中使用):
let operations: Array = [{
  uri: this.uri,
  type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
  valuesBucket: { name: 'Rose', introduction: 'executeBatch' },
  predicates: this.predicates,
  expectedCount: 0,
  predicatesBackReferences: undefined,
  interrupted: true,
}];
this.DAHelper.executeBatch(this.uri, operations).then((dataquery) => {
  promptAction.showToast({
    message: 'executeBatch_success_toast'
  });
  Logger.info(TAG, 'DAHelper executeBatch result: ' + JSON.stringify(dataquery));
}).catch((error: BusinessError) => {
  promptAction.showToast({
    message: 'executeBatch_failed_toast'
  });
  Logger.error(TAG, `DAHelper executeBatch failed. Cause: ${error.message}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

DataAbility的客户端的接口是由工具接口类对象DataAbilityHelper向外提供,相关接口可参考 DataAbilityHelper模块。

DataAbility权限控制

DataAbility提供数据服务,并不是所有的Ability都有权限读写它,DataAbility有一套权限控制机制来保证数据安全。分为静态权限控制和动态权限控制两部分。

静态权限控制

DataAbility作为服务端,在被拉起的时候,会根据config.json里面配置的权限来进行校验,有"readPermission"、"writePermission"和"Permission"三个配置项,可以不配或者为空。示例如下:

"abilities": [
  ...
  {
    "name": ".DataAbility",
    "srcLanguage": "ets",
    "srcPath": "DataAbility",
    "icon": "$media:icon",
    "description": "$string:DataAbility_desc",
    "type": "data",
    "visible": true,
    "uri": "dataability://com.samples.famodelabilitydevelop.DataAbility",
    "readPermission": "ohos.permission.READ_CONTACTS",
    "writePermission": "ohos.permission.WRITE_CONTACTS"
  },
  ...
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

客户端在拉起DataAbility的时候,需要校验客户端是否有权限拉起该DataAbility。客户端的权限配置在config.json配置文件的"module"对象的"reqPermissions"对象中,示例如下:

{
  ...
  "module": {
    ...
    "reqPermissions": [
      {
        "name": "ohos.permission.READ_CONTACTS"
      },
      {
        "name": "ohos.permission.WRITE_CONTACTS"
      },
      ...
    ],
    ...
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

动态权限控制

静态权限校验只能控制某个DataAbility是否能被另一个Ability或应用拉起,无法精确校验每个读写接口的权限,因为拉起DataAbility的时候,还不知道应用是否需要读写它的数据。

动态权限控制是校验每个数据操作的接口是否有对应的权限。客户端调用数据操作接口所需的权限如下表所示。

表1 接口对应的读写权限配置

需要配置读权限的接口需要配置写权限的接口**据实际操作配置读写权限的接口
query、normalizeUri、denormalizeUri、openfile(传入mode有’r’)insert、batchInsert、delete、update、openfile(传入mode有’w’)executeBatch

对于需要配置读权限的接口,服务端需要配置readPermission,客户端必须申请相应的读权限才能调用相关的接口。

对于需要配置写权限的接口,服务端需要配置writePermission,客户端必须申请相应的写权限才能调用相关的接口。

鸿蒙全栈开发全新学习指南

为了积极培养鸿蒙生态人才,让大家都能学习到鸿蒙开发最新的技术,针对一些在职人员、0基础小白、应届生/计算机专业、鸿蒙爱好者等人群,整理了一套纯血版鸿蒙(HarmonyOS Next)全栈开发技术的学习路线【包含了大厂APP实战项目开发】。

本路线共分为四个阶段:

第一阶段:鸿蒙初中级开发必备技能

在这里插入图片描述

第二阶段:鸿蒙南北双向高工技能基础:gitee.com/MNxiaona/733GH

第三阶段:应用开发中高级就业技术

第四阶段:全网首发-工业级南向设备开发就业技术:gitee.com/MNxiaona/733GH

鸿蒙开发面试真题(含参考答案):gitee.com/MNxiaona/733GH

写在最后

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing?,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新学习资源,请移步前往小编:gitee.com/MNxiaona/733GH

鸿蒙开发学习资料领取!!!
微信名片
注:本文转载自blog.csdn.net的OpenHarmony_小贾的文章"https://blog.csdn.net/maniuT/article/details/139987467"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top