• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Event Management
2
3<!--Kit: Calendar Kit-->
4<!--Subsystem: Applications-->
5<!--Owner: @qq_42718467-->
6<!--Designer: @huangxinwei-->
7<!--Tester: @z30055209-->
8<!--Adviser: @ge-yafang-->
9
10An event refers to a specific event or activity arrangement. Event management is to arrange events or activities to effectively use related resources, improve productivity and efficiency, and enable users to better manage time and tasks.
11
12An [Event](../reference/apis-calendar-kit/js-apis-calendarManager.md#event) in Calendar Kit belongs to a [Calendar](../reference/apis-calendar-kit/js-apis-calendarManager.md#calendar). A calendar can contain multiple events, but an event can only belong to one calendar.
13
14After obtaining the **Calendar** object, you can create, delete, modify and query the events belonging to this calendar. When creating or modifying an event, you can set the event title, start time, end time, event type, event location, event reminder, and event recurrence rule to facilitate event management.
15
16## Available APIs
17
18The table below lists the main APIs used for event management. For details about more APIs and their usage, see [@ohos.calendarManager](../reference/apis-calendar-kit/js-apis-calendarManager.md).
19
20| API                                     | Description                                            |
21| ----------------------------------------- |------------------------------------------------|
22| getCalendarManager(context: Context): CalendarManager | Obtains a **CalendarManager** object based on the context.              |
23| createCalendar(calendarAccount: CalendarAccount): Promise\<Calendar> | Creates a **Calendar** object based on the calendar account information. This API uses a promise to return the result.        |
24| addEvent(event: Event): Promise\<number>  | Adds an event, with no event ID specified in **Event**. This API uses a promise to return the result.             |
25| editEvent(event: Event): Promise\<number> | Edits an event on the event creation page, with no event ID specified in **Event**. This API uses a promise to return the result.|
26| deleteEvent(id: number): Promise\<void>   | Deletes an event with the specified ID. This API uses a promise to return the result.                    |
27| updateEvent(event: Event): Promise\<void> | Updates an event. This API uses a promise to return the result.                           |
28| getEvents(eventFilter?: EventFilter, eventKey?: (keyof Event)[]): Promise\<Event[]> | Obtains all events in a calendar that match the filter criteria. This API uses a promise to return the result.        |
29
30## How to Develop
31
321. Import dependencies.
33
34   ```ts
35   // entry/src/main/ets/entryability/EntryAbility.ets
36   import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit';
37   import { BusinessError } from '@kit.BasicServicesKit';
38   import { calendarManager } from '@kit.CalendarKit';
39   import { window } from '@kit.ArkUI';
40   ```
41
422. 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).
43
443. Obtain the **calendarMgr** object based on the context to manage calendars. You are advised to perform managements in the **EntryAbility.ets** file.
45
46   ```ts
47   // entry/src/main/ets/entryability/EntryAbility.ets
48   export let calendarMgr: calendarManager.CalendarManager | null = null;
49
50   export let mContext: common.UIAbilityContext | null = null;
51
52   export default class EntryAbility extends UIAbility {
53     onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
54       console.info("Ability onCreate");
55     }
56
57     onDestroy(): void {
58       console.info("Ability onDestroy");
59     }
60
61     onWindowStageCreate(windowStage: window.WindowStage): void {
62       // Main window is created, set main page for this ability
63       console.info("Ability onWindowStageCreate");
64       windowStage.loadContent('pages/Index', (err, data) => {
65         if (err.code) {
66           console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`);
67           return;
68         }
69         console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`);
70       });
71       mContext = this.context;
72       const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR'];
73       let atManager = abilityAccessCtrl.createAtManager();
74       atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => {
75         console.info(`get Permission success, result: ${JSON.stringify(result)}`);
76         calendarMgr = calendarManager.getCalendarManager(mContext);
77       }).catch((error: BusinessError) => {
78         console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`);
79       })
80     }
81
82     onWindowStageDestroy(): void {
83       // Main window is destroyed, release UI related resources
84       console.info("Ability onWindowStageDestroy");
85     }
86
87     onForeground(): void {
88       // Ability has brought to foreground
89       console.info("Ability onForeground");
90     }
91
92     onBackground(): void {
93       // Ability has back to background
94       console.info("Ability onBackground");
95     }
96   }
97   ```
98
994. Create a **Calendar** object based on the calendar account information to manage events. Set the calendar configuration information, such as event reminder and calendar color, as required.
100
101   ```ts
102   // Index.ets
103   import { BusinessError } from '@kit.BasicServicesKit';
104   import { calendarMgr } from '../entryability/EntryAbility';
105   import { calendarManager } from '@kit.CalendarKit';
106
107   let calendar: calendarManager.Calendar | undefined = undefined;
108   // Specify the calendar account information.
109   const calendarAccount: calendarManager.CalendarAccount = {
110     name: 'MyCalendar',
111     type: calendarManager.CalendarType.LOCAL,
112     // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI.
113     displayName: 'MyCalendar'
114   };
115   // Calendar configuration information.
116   const config: calendarManager.CalendarConfig = {
117     // Enable the event reminder.
118     enableReminder: true,
119     // Set the calendar color.
120     color: '#aabbcc'
121   };
122   // Create a calendar.
123   calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => {
124     console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`);
125     calendar = data;
126     // Ensure that the calendar is successfully created before managing related events.
127
128     // Set the calendar configuration information, including event reminder and calendar color.
129     calendar.setConfig(config).then(() => {
130       console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`);
131     }).catch((err: BusinessError) => {
132       console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`);
133     });
134     // ...
135   }).catch((error: BusinessError) => {
136     console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`);
137   });
138   ```
139
1405. Add an event to the current calendar without specifying the event ID.
141
142   When creating an event, you can set the event title, start time, end time, event type, event location, event reminder time, and event recurrence rule.
143
144   After an event is created, an event ID is returned as the unique identifier. You can update or delete the event based on the event ID.
145
146   Currently, you can create an event in either of the following methods:
147
148   Method 1: Use **addEvent()** to create a single event or **addEvents()** to create events in batches. The following describes how to create a single event.
149
150   Method 2: After obtaining the **calendarManager** object, you can use **editEvent()** to create a single event. In this case, the event creation page is displayed, where you can perform related operations to create an event. Note that **editEvent()** does not support the creation of custom periodic events.
151
152   ```ts
153   // Index.ets
154   let eventId : number | undefined = undefined;
155   const date = new Date();
156   const event: calendarManager.Event = {
157     // Event title.
158     title: 'title',
159     // Event type. Third-party developers are not advised to use calendarManager.EventType.IMPORTANT. Important events do not support quick service redirection and custom reminder time.
160     type: calendarManager.EventType.NORMAL,
161     // Start time of the event.
162     startTime: date.getTime(),
163     // End time of the event.
164     endTime: date.getTime() + 60 * 60 * 1000,
165     // A 10-minute-countdown reminder before the start time.
166     reminderTime: [10],
167     // Event recurrence rule. Mandatory if the event is a periodic one; otherwise, optional.
168     recurrenceRule: {
169       // Event recurrence frequency, which can be daily, weekly, monthly, or yearly.
170       recurrenceFrequency: calendarManager.RecurrenceFrequency.DAILY,
171       // Number of event recurrence times. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used.
172       count: 100,
173       // Interval for event recurrence, which is related to recurrenceFrequency. This example indicates that the event is repeated every two days.
174       interval: 2,
175       // Event expiration time. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used.
176       expire: date.getTime() + 60 * 60 * 1000 * 3,
177       // Excluded date. If set, the specified date is excluded from the repeated event.
178       excludedDates: [date.getTime() + 60 * 60 * 1000 * 2]
179     },
180     // Event service (optional). Set this attribute for the event that requires the one-click service.
181     service: {
182       // Service type, for example, TRIP, MEETING, or WATCHING.
183       type: calendarManager.ServiceType.TRIP,
184       // Service URI, in the DeepLink format, which supports redirection to a specific page of a third-party application. To use the DeepLink mode, you need to register your application with the Huawei HAG Cloud with the registration information including the application bundle name and application service type.
185       // DeepLink includes scheme, host, path, and parameters (excluding values).
186       uri: 'xxx://xxx.xxx.com/xxx',
187       // Service auxiliary description (optional).
188       description: 'One-click service'
189     }
190
191   };
192   // Method 1
193   calendar.addEvent(event).then((data: number) => {
194     console.info(`Succeeded in adding event, id -> ${data}`);
195     eventId = data;
196   }).catch((err: BusinessError) => {
197     console.error(`Failed to addEvent. Code: ${err.code}, message: ${err.message}`);
198   });
199   // Method 2
200   const eventInfo: calendarManager.Event = {
201     // Event title.
202     title: 'title',
203     // Event type.
204     type: calendarManager.EventType.NORMAL,
205     // Start time of the event.
206     startTime: date.getTime(),
207     // End time of the event.
208     endTime: date.getTime() + 60 * 60 * 1000
209   };
210   calendarMgr?.editEvent(eventInfo).then((id: number): void => {
211     console.info(`create Event id = ${id}`);
212     eventId = id;
213   }).catch((err: BusinessError) => {
214     console.error(`Failed to create Event. Code: ${err.code}, message: ${err.message}`);
215   });
216   ```
217
2186. Update information about a specified event based on the event ID.
219
220   ```ts
221   // Index.ets
222   const updateEvent: calendarManager.Event = {
223     title: 'updateTitle',
224     description: 'updateEventTest',
225     type: calendarManager.EventType.NORMAL,
226     id: eventId,
227     startTime: date.getTime(),
228     endTime: date.getTime() + 60 * 60 * 1000
229   };
230   calendar.updateEvent(updateEvent).then(() => {
231     console.info(`Succeeded in updating event`);
232   }).catch((err: BusinessError) => {
233     console.error(`Failed to update event. Code: ${err.code}, message: ${err.message}`);
234   });
235   ```
236
2377. Query all events belonging to the current calendar. Due to data privacy and security concerns, applications with restricted permissions cannot obtain account information created by other applications. Query results vary with query conditions and fields.
238
239   If no query condition or field is set, all events of the specified calendar can be queried.
240   ```ts
241   calendar.getEvents().then((data: calendarManager.Event[]) => {
242     console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
243   }).catch((err: BusinessError) => {
244     console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
245   });
246   ```
247
248   You can also query events by the event ID, start time and end time of the event, or event title.
249   ```ts
250   // Query by the event ID.
251   const filterId = calendarManager.EventFilter.filterById([eventId]);
252   calendar.getEvents(filterId).then((data: calendarManager.Event[]) => {
253     console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
254   }).catch((err: BusinessError) => {
255     console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
256   });
257
258   // Query by the event title.
259   const filterTitle = calendarManager.EventFilter.filterByTitle('update');
260   calendar.getEvents(filterTitle).then((data: calendarManager.Event[]) => {
261     console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
262   }).catch((err: BusinessError) => {
263     console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
264   });
265
266   // Query by the start time and end time.
267   const filterTime = calendarManager.EventFilter.filterByTime(1686931200000, 1687017600000);
268   calendar.getEvents(filterTime).then((data: calendarManager.Event[]) => {
269     console.info(`Succeeded in getting events filter by time, data -> ${JSON.stringify(data)}`);
270   }).catch((err: BusinessError) => {
271     console.error(`Failed to filter by time. Code: ${err.code}, message: ${err.message}`);
272   });
273   ```
274
2758. Delete a specified event by event ID. You can use **deleteEvent()** to create a single event or use **deleteEvents()** to delete events in batches. The following describes how to delete a single event.
276
277   ```ts
278   // Index.ets
279   calendar.deleteEvent(eventId).then(() => {
280      console.info("Succeeded in deleting event");
281    }).catch((err: BusinessError) => {
282      console.error(`Failed to delete event. Code: ${err.code}, message: ${err.message}`);
283   });
284   ```
285