Read the original article:How to use Calendar Kit
Context
Calendar Kit is a framework provided by HarmonyOS that allows applications to interact with the device’s native calendar system. It enables developers to create, view, update, and delete calendar events directly from their applications. This capability is especially useful in productivity, scheduling, event reminder, or personal assistant apps.
Description
The Calendar Kit is accessible through the CalendarKit module. It provides functionality for:
- Inserting calendar events (
addEvent) - Querying existing events (getEvents)
- Deleting events (
deleteEvent) - (Optionally) handling recurring events
- Adding reminders (if supported)
To use Calendar Kit effectively, the application must declare and request the appropriate permissions (READ_CALENDAR and WRITE_CALENDAR).
Solution / Approach
1. Declare required permissions
//module.json5
"requestPermissions":[
{
"name" : "ohos.permission.READ_CALENDAR",
"reason": "$string:module_desc",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.WRITE_CALENDAR",
"reason": "$string:module_desc",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
},
]
2. Obtain the calendarMgr object based on the context to manage calendars. You are advised to perform managements in the EntryAbility.ets file.
// entry/src/main/ets/entryability/EntryAbility.ets
export let calendarMgr: calendarManager.CalendarManager | null = null;
export let mContext: common.UIAbilityContext | null = null;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
console.info("Ability onCreate");
}
onDestroy(): void {
console.info("Ability onDestroy");
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
console.info("Ability onWindowStageCreate");
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`);
});
mContext = this.context;
const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR'];
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => {
console.info(`get Permission success, result: ${JSON.stringify(result)}`);
calendarMgr = calendarManager.getCalendarManager(mContext);
}).catch((error: BusinessError) => {
console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`);
})
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
console.info("Ability onWindowStageDestroy");
}
onForeground(): void {
// Ability has brought to foreground
console.info("Ability onForeground");
}
onBackground(): void {
// Ability has back to background
console.info("Ability onBackground");
}
}
3. Insert a calendar event
// Index.ets
let eventId : number | undefined = undefined;
const date = new Date();
const event: calendarManager.Event = {
// Event title.
title: 'title',
// 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.
type: calendarManager.EventType.NORMAL,
// Start time of the event.
startTime: date.getTime(),
// End time of the event.
endTime: date.getTime() + 60 * 60 * 1000,
// A 10-minute-countdown reminder before the start time.
reminderTime: [10],
// Event recurrence rule. Mandatory if the event is a periodic one; otherwise, optional.
recurrenceRule: {
// Event recurrence frequency, which can be daily, weekly, monthly, or yearly.
recurrenceFrequency: calendarManager.RecurrenceFrequency.DAILY,
// 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.
count: 100,
// Interval for event recurrence, which is related to recurrenceFrequency. This example indicates that the event is repeated every two days.
interval: 2,
// Event expiration time. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used.
expire: date.getTime() + 60 * 60 * 1000 * 3,
// Excluded date. If set, the specified date is excluded from the repeated event.
excludedDates: [date.getTime() + 60 * 60 * 1000 * 2]
},
// Event service (optional). Set this attribute for the event that requires the one-click service.
service: {
// Service type, for example, TRIP, MEETING, or WATCHING.
type: calendarManager.ServiceType.TRIP,
// 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.
// DeepLink includes scheme, host, path, and parameters (excluding values).
uri: 'xxx://xxx.xxx.com/xxx',
// Service auxiliary description (optional).
description: 'One-click service'
}
};
// Method 1
calendar.addEvent(event).then((data: number) => {
console.info(`Succeeded in adding event, id -> ${data}`);
eventId = data;
}).catch((err: BusinessError) => {
console.error(`Failed to addEvent. Code: ${err.code}, message: ${err.message}`);
});
// Method 2
const eventInfo: calendarManager.Event = {
// Event title.
title: 'title',
// Event type.
type: calendarManager.EventType.NORMAL,
// Start time of the event.
startTime: date.getTime(),
// End time of the event.
endTime: date.getTime() + 60 * 60 * 1000
};
calendarMgr?.editEvent(eventInfo).then((id: number): void => {
console.info(`create Event id = ${id}`);
eventId = id;
}).catch((err: BusinessError) => {
console.error(`Failed to create Event. Code: ${err.code}, message: ${err.message}`);
});
4. Update information about a specified event based on the event ID.
// Index.ets
const updateEvent: calendarManager.Event = {
title: 'updateTitle',
description: 'updateEventTest',
type: calendarManager.EventType.NORMAL,
id: eventId,
startTime: date.getTime(),
endTime: date.getTime() + 60 * 60 * 1000
};
calendar.updateEvent(updateEvent).then(() => {
console.info(`Succeeded in updating event`);
}).catch((err: BusinessError) => {
console.error(`Failed to update event. Code: ${err.code}, message: ${err.message}`);
});
5.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.
If no query condition or field is set, all events of the specified calendar can be queried.
calendar.getEvents().then((data: calendarManager.Event[]) => {
console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
});
You can also query events by the event ID, start time and end time of the event, or event title.
// Query by the event ID.
const filterId = calendarManager.EventFilter.filterById([eventId]);
calendar.getEvents(filterId).then((data: calendarManager.Event[]) => {
console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
});
// Query by the event title.
const filterTitle = calendarManager.EventFilter.filterByTitle('update');
calendar.getEvents(filterTitle).then((data: calendarManager.Event[]) => {
console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`);
});
// Query by the start time and end time.
const filterTime = calendarManager.EventFilter.filterByTime(1686931200000, 1687017600000);
calendar.getEvents(filterTime).then((data: calendarManager.Event[]) => {
console.info(`Succeeded in getting events filter by time, data -> ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`Failed to filter by time. Code: ${err.code}, message: ${err.message}`);
});
6. 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.
// Index.ets
calendar.deleteEvent(eventId).then(() => {
console.info("Succeeded in deleting event");
}).catch((err: BusinessError) => {
console.error(`Failed to delete event. Code: ${err.code}, message: ${err.message}`);
});
Key Takeaways
- Calendar Kit enables your app to interact with the native calendar system on HarmonyOS devices.
- You can insert, view, and delete events using straightforward API calls.
- Runtime permission handling is mandatory for reading/writing calendar data.
- Asynchronous methods ensure smooth and responsive UI integration.
- The API is simple and ArkTS makes it easy to implement.
Top comments (0)