1# Event Management 2 3An 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. 4 5An [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. 6 7After 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. 8 9## Available APIs 10 11The 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). 12 13| API | Description | 14| ------------------------------------------------------------ | ------------------------------------------------------------ | 15| getCalendarManager(context : Context): CalendarManager | Obtains a **CalendarManager** object based on the context. | 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| addEvent(event: Event): Promise\<number> | Creates an event, with no event ID specified in **Event**. This API uses a promise to return the result. | 18| editEvent(event: Event): Promise\<number> | Creates a single event. If the input parameter **Event** is not set to the event ID, the event creation screen is displayed when this API is called. This API uses a promise to return the result.| 19| deleteEvent(id: number): Promise\<void> | Deletes an event with the specified ID. This API uses a promise to return the result. | 20| updateEvent(event: Event): Promise\<void> | Updates an event. This API uses a promise to return the result. | 21| 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. | 22 23## How to Develop 24 251. Import dependencies. 26 27 ```ts 28 // entry/src/main/ets/entryability/EntryAbility.ets 29 import {abilityAccessCtrl,AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; 30 import { BusinessError } from '@kit.BasicServicesKit'; 31 import { calendarManager } from '@kit.CalendarKit'; 32 import { window } from '@kit.ArkUI'; 33 ``` 34 352. 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). 36 373. Obtain the **calendarMgr** object based on the context to manage calendars. You are advised to perform managements in the **EntryAbility.ets** file. 38 39 ```ts 40 // entry/src/main/ets/entryability/EntryAbility.ets 41 export let calendarMgr: calendarManager.CalendarManager | null = null; 42 43 export let mContext: common.UIAbilityContext | null = null; 44 45 export default class EntryAbility extends UIAbility { 46 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 47 console.info("Ability onCreate"); 48 } 49 50 onDestroy(): void { 51 console.info("Ability onDestroy"); 52 } 53 54 onWindowStageCreate(windowStage: window.WindowStage): void { 55 // Main window is created, set main page for this ability 56 console.info("Ability onWindowStageCreate"); 57 windowStage.loadContent('pages/Index', (err, data) => { 58 if (err.code) { 59 console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`); 60 return; 61 } 62 console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); 63 }); 64 mContext = this.context; 65 const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR']; 66 let atManager = abilityAccessCtrl.createAtManager(); 67 atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => { 68 console.log(`get Permission success, result: ${JSON.stringify(result)}`); 69 calendarMgr = calendarManager.getCalendarManager(mContext); 70 }).catch((error: BusinessError) => { 71 console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`); 72 }) 73 } 74 75 onWindowStageDestroy(): void { 76 // Main window is destroyed, release UI related resources 77 console.info("Ability onWindowStageDestroy"); 78 } 79 80 onForeground(): void { 81 // Ability has brought to foreground 82 console.info("Ability onForeground"); 83 } 84 85 onBackground(): void { 86 // Ability has back to background 87 console.info("Ability onBackground"); 88 } 89 } 90 ``` 91 924. 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. 93 94 ```ts 95 // Index.ets 96 import { BusinessError } from '@kit.BasicServicesKit'; 97 import { calendarMgr } from '../entryability/EntryAbility'; 98 import { calendarManager } from '@kit.CalendarKit'; 99 100 let calendar: calendarManager.Calendar | undefined = undefined; 101 // Specify the calendar account information. 102 const calendarAccount: calendarManager.CalendarAccount = { 103 name: 'MyCalendar', 104 type: calendarManager.CalendarType.LOCAL, 105 // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI. 106 displayName: 'MyCalendar' 107 }; 108 // Calendar configuration information. 109 const config: calendarManager.CalendarConfig = { 110 // Enable the event reminder. 111 enableReminder: true, 112 // Set the calendar color. 113 color: '#aabbcc' 114 }; 115 // Create a calendar. 116 calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => { 117 console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`); 118 calendar = data; 119 // Ensure that the calendar is successfully created before managing related events. 120 121 // Set the calendar configuration information, including event reminder and calendar color. 122 calendar.setConfig(config).then(() => { 123 console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`); 124 }).catch((err: BusinessError) => { 125 console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`); 126 }); 127 // ... 128 }).catch((error: BusinessError) => { 129 console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`); 130 }); 131 ``` 132 1335. Add an event to the current calendar without specifying the event ID. 134 135 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. 136 137 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. 138 139 Currently, you can create an event in either of the following methods: 140 141 Method 1: Use the **addEvent()** or **addEvents()** API to create an event in the calendar. You can use the **addEvent()** API to create a single event or use the **addEvents()** API to create events in batches. The following describes how to create a single event. 142 143 Method 2: After obtaining the **calendarManager** object, you can use the **editEvent()** API 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. 144 145 ```ts 146 // Index.ets 147 let eventId : number | undefined = undefined; 148 const date = new Date(); 149 const event: calendarManager.Event = { 150 // Event title. 151 title: 'title', 152 // 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. 153 type: calendarManager.EventType.NORMAL, 154 // Start time of the event. 155 startTime: date.getTime(), 156 // End time of the event. 157 endTime: date.getTime() + 60 * 60 * 1000, 158 // A 10-minute-countdown reminder before the start time. 159 reminderTime: [10], 160 // Event recurrence rule. Mandatory if the event is a periodic one; otherwise, optional. 161 recurrenceRule: { 162 // Event recurrence frequency, which can be daily, weekly, monthly, or yearly. 163 recurrenceFrequency: calendarManager.RecurrenceFrequency.DAILY, 164 // 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. 165 count: 100, 166 // Interval for event recurrence, which is related to recurrenceFrequency. This example indicates that the event is repeated every two days. 167 interval: 2, 168 // Event expiration time. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used. 169 expire: date.getTime() + 60 * 60 * 1000 * 3, 170 // Excluded date. If set, the specified date is excluded from the repeated event. 171 excludedDates: [date.getTime() + 60 * 60 * 1000 * 2] 172 }, 173 // Event service (optional). Set this attribute for the event that requires the one-click service. 174 service: { 175 // Service type, for example, TRIP, MEETING, or WATCHING. 176 type: calendarManager.ServiceType.TRIP, 177 // 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. 178 // DeepLink includes scheme, host, path, and parameters (excluding values). 179 uri: 'xxx://xxx.xxx.com/xxx', 180 // Service auxiliary description (optional). 181 description: 'One-click service' 182 } 183 184 }; 185 // Method 1 186 calendar.addEvent(event).then((data: number) => { 187 console.info(`Succeeded in adding event, id -> ${data}`); 188 eventId = data; 189 }).catch((err: BusinessError) => { 190 console.error(`Failed to addEvent. Code: ${err.code}, message: ${err.message}`); 191 }); 192 // Method 2 193 const eventInfo: calendarManager.Event = { 194 // Event title. 195 title: 'title', 196 // Event type. 197 type: calendarManager.EventType.NORMAL, 198 // Start time of the event. 199 startTime: date.getTime(), 200 // End time of the event. 201 endTime: date.getTime() + 60 * 60 * 1000 202 }; 203 calendarMgr?.editEvent(eventInfo).then((id: number): void => { 204 console.info(`create Event id = ${id}`); 205 eventId = id; 206 }).catch((err: BusinessError) => { 207 console.error(`Failed to create Event. Code: ${err.code}, message: ${err.message}`); 208 }); 209 ``` 210 2116. Update information about a specified event based on the event ID. 212 213 ```ts 214 // Index.ets 215 const updateEvent: calendarManager.Event = { 216 title: 'updateTitle', 217 description: 'updateEventTest', 218 type: calendarManager.EventType.NORMAL, 219 id: eventId, 220 startTime: date.getTime(), 221 endTime: date.getTime() + 60 * 60 * 1000 222 }; 223 calendar.updateEvent(updateEvent).then(() => { 224 console.info(`Succeeded in updating event`); 225 }).catch((err: BusinessError) => { 226 console.error(`Failed to update event. Code: ${err.code}, message: ${err.message}`); 227 }); 228 ``` 229 2307. 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. 231 232 If no query condition or field is set, all events of the specified calendar can be queried. 233 ```ts 234 calendar.getEvents().then((data: calendarManager.Event[]) => { 235 console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); 236 }).catch((err: BusinessError) => { 237 console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); 238 }); 239 ``` 240 241 You can also query events by the event ID, start time and end time of the event, or event title. 242 ```ts 243 // Query by the event ID. 244 const filterId = calendarManager.EventFilter.filterById([eventId]); 245 calendar.getEvents(filterId).then((data: calendarManager.Event[]) => { 246 console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); 247 }).catch((err: BusinessError) => { 248 console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); 249 }); 250 251 // Query by the event title. 252 const filterTitle = calendarManager.EventFilter.filterByTitle('update'); 253 calendar.getEvents(filterTitle).then((data: calendarManager.Event[]) => { 254 console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); 255 }).catch((err: BusinessError) => { 256 console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); 257 }); 258 259 // Query by the start time and end time. 260 const filterTime = calendarManager.EventFilter.filterByTime(1686931200000, 1687017600000); 261 calendar.getEvents(filterTime).then((data: calendarManager.Event[]) => { 262 console.info(`Succeeded in getting events filter by time, data -> ${JSON.stringify(data)}`); 263 }).catch((err: BusinessError) => { 264 console.error(`Failed to filter by time. Code: ${err.code}, message: ${err.message}`); 265 }); 266 ``` 267 2688. Delete a specified event by event ID. You can use the **deleteEvent()** API to create a single event or use the **deleteEvents()** API to delete events in batches. The following describes how to delete a single event. 269 270 ```ts 271 // Index.ets 272 calendar.deleteEvent(eventId).then(() => { 273 console.info("Succeeded in deleting event"); 274 }).catch((err: BusinessError) => { 275 console.error(`Failed to delete event. Code: ${err.code}, message: ${err.message}`); 276 }); 277 ``` 278