Schedule Management
A schedule refers to the arrangement of specific events or activities. Schedule management involves planning and controlling these events and activities to more effectively utilize relevant resources, improve productivity and efficiency, and enable people to better manage their time and tasks.
In Calendar Kit, a schedule [Event] belongs to a corresponding calendar account [Calendar]. A calendar account can contain multiple schedules, and each schedule belongs to only one Calendar.
Once the calendar account object is obtained, you can manage the schedules under that account, including creating, deleting, modifying, and querying schedules. When creating or modifying a schedule, you can set relevant information such as the schedule's title, start time, end time, type, location, reminder time, and recurrence rules to achieve richer and more effective schedule management.
Development Steps
1、Import relevant dependencies.
// entry/src/main/ets/entryability/EntryAbility.ets
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';
2、Request Permissions. When using Calendar Kit, you need to declare the permissions required for reading and writing calendar schedules in module.json5: ohos.permission.READ_CALENDAR and ohos.permission.WRITE_CALENDAR.
3、Obtain the Calendar Manager Object. Retrieve the calendar manager object calendarMgr based on the context to manage calendar accounts. This operation is recommended 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.log(`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");
}
}
4、Create a Calendar object based on calendar account information to manage schedules. Configure calendar settings, such as enabling schedule reminders and setting the calendar account color as needed.
// Index.ets
import { BusinessError } from '@kit.BasicServicesKit';
import { calendarMgr } from '../entryability/EntryAbility';
import { calendarManager } from '@kit.CalendarKit';
let calendar: calendarManager.Calendar | undefined = undefined;
const calendarAccount: calendarManager.CalendarAccount = {
name: 'MyCalendar',
type: calendarManager.CalendarType.LOCAL,
displayName: 'MyCalendar'
};
const config: calendarManager.CalendarConfig = {
enableReminder: true,
color: '#aabbcc'
};
calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => {
console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`);
calendar = data;
calendar.setConfig(config).then(() => {
console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`);
}).catch((err: BusinessError) => {
console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`);
});
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`);
});
5、To add a calendar event under the current calendar account, note that the event ID does not need to be filled in the input parameters.
When creating an event, you can set relevant information such as the event title, start time, end time, event type, location, reminder time, and recurrence rules.
Once the event is successfully created, an event ID will be returned as the unique identifier of the event. You can use this ID to update or delete the specified event later.
Currently, there are two ways to create events:
Method 1: Create events through the addEvent() or addEvents() interface under the calendar account. The addEvent() interface is used to create a single event, while addEvents() can create multiple events in batches. Here is an example of creating a single event:
Method 2: After obtaining the calendar manager object, use the editEvent() interface to create a single event. When calling this interface, it will jump to the event creation page, where you can complete the event creation through relevant operations. Note that editEvent() does not support custom periodic event creation.
// Index.ets
let eventId : number | undefined = undefined;
const date = new Date();
const event: calendarManager.Event = {
title: 'title',
type: calendarManager.EventType.NORMAL,
startTime: date.getTime(),
endTime: date.getTime() + 60 * 60 * 1000,
reminderTime: [10],
recurrenceRule: {
recurrenceFrequency: calendarManager.RecurrenceFrequency.DAILY,
count: 100,
interval: 2,
expire: date.getTime() + 60 * 60 * 1000 * 3,
excludedDates: [date.getTime() + 60 * 60 * 1000 * 2]
},
service: {
type: calendarManager.ServiceType.TRIP,
uri: 'xxx://xxx.xxx.com/xxx',
description: ''
}
};
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}`);
});
const eventInfo: calendarManager.Event = {
title: 'title',
type: calendarManager.EventType.NORMAL,
startTime: date.getTime(),
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}`);
});
6、Update the specified schedule according to the schedule ID and modify the relevant information of the schedule.
// 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}`);
});
7、Query all schedules under the current calendar account. Due to data privacy and security considerations, apps with permission controls cannot access schedule information created by others. Different query results are returned based on different query conditions and fields.
When there are no query conditions or fields, all schedules under the specified calendar account 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}`);
});
It also supports querying schedules based on search criteria such as schedule ID, schedule start and end times, and schedule title.
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}`);
});
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}`);
});
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}`);
});
8、Delete a specified schedule by its schedule ID. You can delete a single schedule using the deleteEvent() interface or batch delete specified schedules using the deleteEvents() interface. Here is an example of deleting a single specified schedule.
// 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}`);
});
Top comments (0)