• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import type common from '@ohos.app.ability.common';
2import fs from '@ohos.file.fs';
3import Logger from './Logger';
4
5const TAG = '[Sample_StatePersistence]';
6const DATA_SIZE = 6;
7const PROCESS_FILE_NAME = '/Process.txt';
8
9function getConditionIDtoFile(context: common.Context, fileName: string): string {
10  Logger.debug(TAG, 'getConditionIDtoFile call');
11  if (context === undefined || context === null || typeof fileName !== 'string' || fileName === '') {
12    Logger.error(TAG, `getConditionIDtoFile failed, context : ${JSON.stringify(context)}`);
13    return '';
14  }
15
16  try {
17    let filePath = context.filesDir + fileName;
18    let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
19    let buff = new ArrayBuffer(DATA_SIZE);
20    let num = fs.readSync(file.fd, buff);
21    let conditionID = String.fromCharCode.apply(null, new Uint8Array(buff));
22    Logger.info(TAG, `getConditionIDtoFile : ${conditionID.length} ${conditionID}, ${num} ${filePath}`);
23    fs.closeSync(file);
24    return conditionID;
25  } catch (err) {
26    Logger.error(TAG, `getConditionIDtoFile err : ${JSON.stringify(err)}`);
27    return '';
28  }
29}
30
31function updateConditionIDtoFile(context: common.Context, conditionID: string, fileName: string): void {
32  Logger.debug(TAG, 'updateConditionIDtoFile call');
33  if (context === undefined || context === null ||
34  typeof conditionID !== 'string' || conditionID === '' ||
35  typeof fileName !== 'string' || fileName === '') {
36    Logger.error(TAG, `updateConditionIDtoFile failed, conditionID : ${JSON.stringify(conditionID)}, context : ${JSON.stringify(context)}`);
37    return;
38  }
39
40  try {
41    let filePath = context.filesDir + fileName;
42    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
43    let num = fs.writeSync(file.fd, conditionID);
44    fs.closeSync(file);
45    Logger.info(TAG, `updateConditionIDtoFile : ${conditionID}, ${num} ${filePath}`);
46  } catch (err) {
47    Logger.error(TAG, `updateConditionIDtoFile err : ${JSON.stringify(err)}`);
48  }
49}
50
51export function getProcessConditionID(context: common.Context): string {
52  return getConditionIDtoFile(context, PROCESS_FILE_NAME);
53}
54
55export function saveProcessConditionID(context: common.Context, conditionID: string): void {
56  updateConditionIDtoFile(context, conditionID, PROCESS_FILE_NAME);
57}