Calendar Management
Calendar is used to store and manage personal or team events. Users can easily view, edit, and share event information on the calendar.
CalendarManager is used to manage Calendar, which includes CalendarAccount and CalendarConfig.
You can create an application-specific calendar, and add, delete, update, and query this calendar. In addition, each Event belongs to a specific Calendar and can be managed by using the Calendar. For details, see Event Management.
Available APIs
The table below lists the main APIs used for calendar management. For details about more APIs and their usage, see @ohos.calendarManager.
| API | Description |
|---|---|
| getCalendarManager(context: Context): CalendarManager | Obtains the CalendarManager object based on the context to manage calendars. |
| createCalendar(calendarAccount: CalendarAccount): Promise<Calendar> | Creates a Calendar object based on the calendar account information. This API uses a promise to return the result. |
| getCalendar(calendarAccount?: CalendarAccount): Promise<Calendar> | Obtains the default or specified Calendar object. This API uses a promise to return the result. 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. |
| getAllCalendars(): Promise<Calendar[]> | Obtains the created and default Calendar objects of the current application. This API uses a promise to return the result. |
| deleteCalendar(calendar: Calendar): Promise<void> | Deletes a specified Calendar object. This API uses a promise to return the result. |
| getConfig(): CalendarConfig | Obtains the calendar configuration information. |
| setConfig(config: CalendarConfig): Promise<void> | Sets the calendar configuration information. This API uses a promise to return the result. |
| getAccount(): CalendarAccount | Obtains the calendar account information. |
How to Develop
-
Import dependencies.
import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { calendarManager } from '@kit.CalendarKit'; import { window } from '@kit.ArkUI'; import { hilog } from '@kit.PerformanceAnalysisKit'; -
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.
-
Obtain the calendarMgr object based on the context to manage calendars. You are advised to perform managements in the EntryAbility.ets file.
const DOMAIN = 0x0000; 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 { hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onCreate"); } onDestroy(): void { hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onDestroy"); } onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onWindowStageCreate"); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); return; } hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); }); 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) => { hilog.info(DOMAIN, 'testTag', 'get Permission success'); calendarMgr = calendarManager.getCalendarManager(mContext); }).catch((error: BusinessError) => { hilog.error(DOMAIN, 'testTag', 'get Permission error, Cause: %{public}s', JSON.stringify(error)); }) } onWindowStageDestroy(): void { // Main window is destroyed, release UI related resources hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onWindowStageDestroy"); } onForeground(): void { // Ability has brought to foreground hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onForeground"); } onBackground(): void { // Ability has back to background hilog.info(DOMAIN, 'testTag', '%{public}s', "Ability onBackground"); } } -
Create a Calendar object based on the calendar account information.
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.
import { BusinessError } from '@kit.BasicServicesKit'; import { calendarMgr } from '../entryability/EntryAbility'; import { calendarManager } from '@kit.CalendarKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const DOMAIN = 0x0000; let calendar: calendarManager.Calendar | undefined = undefined; // Specify the calendar account information. const calendarAccount: calendarManager.CalendarAccount = { // Calendar name. name: 'MyCalendar', // Calendar type. type: calendarManager.CalendarType.LOCAL, // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI. displayName: 'MyCalendar' };// Create a calendar. calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => { hilog.info(DOMAIN, 'testTag', '%{public}s', `Succeeded in creating calendar data->${JSON.stringify(data)}`); calendar = data; // Ensure that the calendar account is created before performing subsequent operations. // ... }).catch((error: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to create calendar. Code: ${error.code}, message: ${error.message}`); }); -
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.
const calendarAccounts: calendarManager.CalendarAccount = { name: 'MyCalendar', type: calendarManager.CalendarType.LOCAL, displayName: 'MyCalendar' }; // Calendar configuration information. calendarMgr?.getCalendar(calendarAccounts, (err, data) => { // Obtain the calendar account. if (err) { hilog.error(DOMAIN, 'testTag', `Failed to get calendar, Code is ${err.code}, message is ${err.message}`); } else { const config: calendarManager.CalendarConfig = { // Enable the event reminder. enableReminder: true, // Set the calendar color. color: '#aabbcc' }; // Set the calendar configuration information. data.setConfig(config).then(() => { hilog.info(DOMAIN, 'testTag', '%{public}s', `Succeeded in setting config, data->${JSON.stringify(config)}`); }).catch((err: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to set config. Code: ${err.code}, message: ${err.message}`); }) } }); -
Query a specified calendar.
calendarMgr?.getCalendar(calendarAccount).then((data: calendarManager.Calendar) => { hilog.info(DOMAIN, 'testTag', '%{public}s', `Succeeded in getting calendar, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to get calendar. Code: ${err.code}, message: ${err.message}`); }); -
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.
calendarMgr?.getCalendar().then((data: calendarManager.Calendar) => { hilog.info(DOMAIN, 'testTag', '%{public}s', `Succeeded in getting calendar, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to get calendar. Code: ${err.code}, message: ${err.message}`); }); -
Obtain the created and default Calendar objects of the current application.
Due to data privacy and security concerns, applications with restricted permissions cannot obtain account information created by other applications.
calendarMgr?.getAllCalendars().then((data: calendarManager.Calendar[]) => { hilog.info(DOMAIN, 'testTag', '%{public}s', `Succeeded in getting all calendars, data -> ${JSON.stringify(data)}`); data.forEach((calendar) => { const account = calendar.getAccount(); hilog.info(DOMAIN, 'testTag', '%{public}s', `account -> ${JSON.stringify(account)}`); }) }).catch((err: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to get all calendars. Code: ${err.code}, message: ${err.message}`); }); -
Delete the specified calendar, whose subordinate events are also deleted.
if (!calendar || calendar === null) { hilog.error(DOMAIN, 'testTag', 'Failed to delete calendar. calendar is null'); return; } calendarMgr?.deleteCalendar(calendar).then(() => { hilog.info(DOMAIN, 'testTag', '%{public}s', "Succeeded in deleting calendar"); }).catch((err: BusinessError) => { hilog.error(DOMAIN, 'testTag', `Failed to delete calendar. Code: ${err.code}, message: ${err.message}`); });