HarmonyOS 日历服务无法读取,没有任何报错可是读出来是空?

已申请日历权限,但是无法读取显示为空,具体demo如下:

import { calendarManager } from '@kit.CalendarKit';

const TAG = "[SystemCalendarManager]"

export function getThisDayStart(date: Date = new Date()): Date {
  let dateTime = new Date(date);
  dateTime = new Date(dateTime.setHours(0));
  dateTime = new Date(dateTime.setMinutes(0));
  dateTime = new Date(dateTime.setSeconds(0));
  dateTime = new Date(dateTime.setMilliseconds(0));
  return dateTime
}

/**
 * 获取当日终点
 * @param date 查询的日期
 */
export function getThisDayEnd(date: Date = new Date()): Date {
  let dateTime = new Date(date);
  dateTime = new Date(dateTime.setHours(23));
  dateTime = new Date(dateTime.setMinutes(59));
  dateTime = new Date(dateTime.setSeconds(59));
  dateTime = new Date(dateTime.setMilliseconds(999));
  return dateTime
}

/**
 * 获取日历内容
 * @param showDate 日期
 * @param context
 * @returns
 */
export async function getSystemCalendarEvents(showDate: Date, context: Context): Promise<void> {
  console.log(TAG, "getSystemCalendarEvents", showDate.toLocaleString())
  if (canIUse("SystemCapability.Applications.CalendarData")) {
    console.log(TAG, "canIUse", "SystemCapability.Applications.CalendarData")
    try {
      let calendarMgr = calendarManager.getCalendarManager(context);
      let calendar = await calendarMgr.getCalendar()
      let filter = calendarManager.EventFilter.filterByTime(
        getThisDayStart(showDate).getTime(),
        getThisDayEnd(showDate).getTime()
      );
      let events: Array<calendarManager.Event> = await calendar.getEvents(filter);
      console.warn(TAG, "getSystemCalendarEvents", JSON.stringify(filter), JSON.stringify(events))
    } catch (err) {
      console.error(TAG, "getSystemCalendarEvents", JSON.stringify(err))
    }
  }
  return
}

最终出来的结果为:

[SystemCalendarManager] getSystemCalendarEvents {} []
阅读 396
1 个回答

calendar获取日程事件是有权限限制的,只能获取本应用创建的日程事件,(系统日历程序权限更高,只有系统日历可以获取所有的日程事件)。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏