• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Calendar Management
2
3Calendar is used to store and manage personal or team events. Users can easily view, edit, and share event information on the calendar.
4
5[CalendarManager](../reference/apis-calendar-kit/js-apis-calendarManager.md#calendarmanager) is used to manage [Calendar](../reference/apis-calendar-kit/js-apis-calendarManager.md#calendar), which includes [CalendarAccount](../reference/apis-calendar-kit/js-apis-calendarManager.md#calendaraccount) and [CalendarConfig](../reference/apis-calendar-kit/js-apis-calendarManager.md#calendarconfig).
6
7You can create an application-specific calendar, and add, delete, update, and query this calendar. In addition, each [Event](../reference/apis-calendar-kit/js-apis-calendarManager.md#event) belongs to a specific Calendar and can be managed by using the Calendar. For details, see [Event Management](calendarmanager-event-developer.md).
8
9## Available APIs
10
11The table below lists the main APIs used for calendar management. For details about more APIs and their usage, see [@ohos.calendarManager](../reference/apis-calendar-kit/js-apis-calendarManager.md).
12
13| API                                                    | Description                                                        |
14| ----------------------------------------------------------- | ------------------------------------------------------------ |
15| getCalendarManager(context: Context): CalendarManager       | Obtains the **CalendarManager** object based on the context to manage calendars. |
16| createCalendar(calendarAccount: CalendarAccount): Promise\<Calendar> | Creates a **Calendar** object based on the calendar account information. This API uses a promise to return the result.|
17| getCalendar(calendarAccount?: CalendarAccount): Promise\<Calendar> | Obtains the default or specified **Calendar** object. This API uses a promise to return the result.<br>The default **Calendar** object is created when the data storage runs for the first time. You can call this API instead of **createCalendar()** to use the default calendar for a new event.|
18| getAllCalendars(): Promise\<Calendar[]>                     | Obtains the created and default **Calendar** objects of the current application. This API uses a promise to return the result.|
19| deleteCalendar(calendar: Calendar): Promise\<void>          | Deletes a specified **Calendar** object. This API uses a promise to return the result.                 |
20| getConfig(): CalendarConfig                                 | Obtains the calendar configuration information.                                          |
21| setConfig(config: CalendarConfig): Promise\<void>           | Sets the calendar configuration information. This API uses a promise to return the result.                     |
22| getAccount(): CalendarAccount                               | Obtains the calendar account information.                                          |
23
24
25## How to Develop
26
271. Import dependencies.
28
29   ```ts
30   // EntryAbility.ets
31   import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit';
32   import { BusinessError } from '@kit.BasicServicesKit';
33   import { calendarManager } from '@kit.CalendarKit';
34   import { window } from '@kit.ArkUI';
35   ```
36
372. Apply for the required permission. When using Calendar Kit, declare the **ohos.permission.READ_CALENDAR** and **ohos.permission.WRITE_CALENDAR** permissions in the **module.json5** file .for reading and writing calendar events. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
38
393. Obtain the **calendarMgr** object based on the context to manage calendars. You are advised to perform managements in the **EntryAbility.ets** file.
40
41   ```ts
42   // EntryAbility.ets
43   export let calendarMgr: calendarManager.CalendarManager | null = null;
44
45   export let mContext: common.UIAbilityContext | null = null;
46
47   export default class EntryAbility extends UIAbility {
48     onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
49       console.info("Ability onCreate");
50     }
51
52     onDestroy(): void {
53       console.info("Ability onDestroy");
54     }
55
56     onWindowStageCreate(windowStage: window.WindowStage): void {
57       // Main window is created, set main page for this ability
58       console.info("Ability onWindowStageCreate");
59       windowStage.loadContent('pages/Index', (err, data) => {
60         if (err.code) {
61           console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`);
62           return;
63         }
64         console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`);
65       });
66       mContext = this.context;
67       const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR'];
68       let atManager = abilityAccessCtrl.createAtManager();
69       atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => {
70         console.info(`get Permission success, result: ${JSON.stringify(result)}`);
71         calendarMgr = calendarManager.getCalendarManager(mContext);
72       }).catch((error: BusinessError) => {
73         console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`);
74       })
75     }
76
77     onWindowStageDestroy(): void {
78       // Main window is destroyed, release UI related resources
79       console.info("Ability onWindowStageDestroy");
80     }
81
82     onForeground(): void {
83       // Ability has brought to foreground
84       console.info("Ability onForeground");
85     }
86
87     onBackground(): void {
88       // Ability has back to background
89       console.info("Ability onBackground");
90     }
91   }
92   ```
93
944. Create a **Calendar** object based on the calendar account information.
95
96   Query the account information and create a calendar when an exception indicating that the calendar does not exist is thrown. Otherwise, the calendar may be created repeatedly.
97
98   ```ts
99   // Index.ets
100   import { BusinessError } from '@kit.BasicServicesKit';
101   import { calendarMgr } from '../entryability/EntryAbility';
102   import { calendarManager } from '@kit.CalendarKit';
103
104   let calendar: calendarManager.Calendar | undefined = undefined;
105   // Specify the calendar account information.
106   const calendarAccount: calendarManager.CalendarAccount = {
107     // Calendar name.
108     name: 'MyCalendar',
109     // Calendar type.
110     type: calendarManager.CalendarType.LOCAL,
111     // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI.
112     displayName: 'MyCalendar'
113   };
114   // Create a calendar.
115   calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => {
116     console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`);
117     calendar = data;
118     // Ensure that the calendar account is created before performing subsequent operations.
119     // ...
120   }).catch((error: BusinessError) => {
121     console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`);
122   });
123   ```
124
1255. After a calendar account is created, its color is black by default. If no color is specified, the display effect of the calendar account in dark mode may be poor on some versions or devices. You need to call **setConfig()** to set calendar configuration information, including event reminder and calendar color.
126
127   ```ts
128   // Index.ets
129   const calendarAccounts: calendarManager.CalendarAccount = {
130     name: 'MyCalendar',
131     type: calendarManager.CalendarType.LOCAL,
132     displayName: 'MyCalendar'
133   };
134   // Calendar configuration information.
135   calendarMgr?.getCalendar(calendarAccounts, (err, data) => {
136     // Obtain the calendar account.
137     if (err) {
138       console.error(`Failed to get calendar, Code is ${err.code}, message is ${err.message}`);
139     } else {
140       const config: calendarManager.CalendarConfig = {
141         // Enable the event reminder.
142         enableReminder: true,
143         // Set the calendar color.
144         color: '#aabbcc'
145       };
146       // Set the calendar configuration information.
147       data.setConfig(config).then(() => {
148         console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`);
149       }).catch((err: BusinessError) => {
150         console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`);
151       })
152     }
153   });
154   ```
155
1566. Query a specified calendar.
157
158    ```ts
159   // Index.ets
160   calendarMgr?.getCalendar(calendarAccount).then((data: calendarManager.Calendar) => {
161     console.info(`Succeeded in getting calendar, data -> ${JSON.stringify(data)}`);
162   }).catch((err: BusinessError) => {
163     console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`);
164   });
165    ```
166
1677. Query a default calendar. The default **Calendar** object is created when the data storage runs for the first time. You can use the default calendar for a new event.
168
169    ```ts
170   // Index.ets
171   calendarMgr?.getCalendar().then((data: calendarManager.Calendar) => {
172     console.info(`Succeeded in getting calendar, data -> ${JSON.stringify(data)}`);
173   }).catch((err: BusinessError) => {
174     console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`);
175   });
176    ```
177
1788. Obtain the created and default **Calendar** objects of the current application.
179
180   Due to data privacy and security concerns, applications with restricted permissions cannot obtain account information created by other applications.
181
182   ```ts
183   // Index.ets
184   calendarMgr?.getAllCalendars().then((data: calendarManager.Calendar[]) => {
185     console.info(`Succeeded in getting all calendars, data -> ${JSON.stringify(data)}`);
186     data.forEach((calendar) => {
187       const account = calendar.getAccount();
188       console.info(`account -> ${JSON.stringify(account)}`);
189     })
190   }).catch((err: BusinessError) => {
191     console.error(`Failed to get all calendars. Code: ${err.code}, message: ${err.message}`);
192   });
193   ```
194
1959. Delete the specified calendar, whose subordinate events are also deleted.
196
197    ```ts
198   // Index.ets
199   calendarMgr?.deleteCalendar(calendar).then(() => {
200     console.info("Succeeded in deleting calendar");
201   }).catch((err: BusinessError) => {
202     console.error(`Failed to delete calendar. Code: ${err.code}, message: ${err.message}`);
203   });
204    ```
205