HarmonyOS 怎么动态获取添加日历的权限,并往日历中写入日程

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

可参考如下demo:

//Index.ets
import { BusinessError } from '@ohos.base';
import { calendarMgr } from '../entryability/EntryAbility';
import { calendarManager } from '@kit.CalendarKit';

@Entry
@Component
struct Index {

  build() {
    Column() {
      Button("添加日程").onClick(()=>{
        let calendar : calendarManager.Calendar | undefined = undefined;
        const date = new Date();
        const event: calendarManager.Event = {
          type: calendarManager.EventType.NORMAL,
          title:"参加读书会",
          startTime: date.getTime(),
          endTime: date.getTime() + 60 * 60 * 1000
        };
        calendarMgr?.getCalendar().then((data: calendarManager.Calendar) => {
          console.info(`Succeeded to get calendar, data -> ${JSON.stringify(data)}`);
          calendar = data;
          calendar.addEvent(event, (err: BusinessError, data: number): void => {
            if (err) {
              console.error(`Failed to addEvent, err -> ${JSON.stringify(err)}`);
            } else {
              console.info(`Succeeded to add event, id -> ${data}`);
            }
          });
        }).catch((err: BusinessError) => {
          console.error(`Failed to get calendar, err -> ${JSON.stringify(err)}`);
        });
      })
    }
    .height('100%')
  }
}
//EntryAbility .ets
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { ContextUtil } from '../ContextUtil';
import { Configuration } from '@ohos.app.ability.Configuration';
import { abilityAccessCtrl, common, ConfigurationConstant,
  PermissionRequestResult,
  Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { calendarManager } from '@kit.CalendarKit';


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(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    ContextUtil.mContext = this.context;
    ContextUtil.mConfiguration = this.context.config;

  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index25', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', 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: ${JSON.stringify(error)}`);
    })
  }


  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }

  onConfigurationUpdate(newConfig: Configuration): void {
    ContextUtil.mConfiguration = newConfig;
  }
}
//module.json5
"requestPermissions": [
{
  "name": "ohos.permission.READ_CALENDAR",
"reason": "$string:reason",
"usedScene": {
  "abilities": [
  "EntryAbility"
  ],
  "when": "inuse"
}
},
{
  "name": "ohos.permission.WRITE_CALENDAR",
"reason": "$string:reason",
"usedScene": {
  "abilities": [
  "EntryAbility"
  ],
  "when": "inuse"
}
}
]

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-calendarmanager-V5#event

分享
微博
QQ
微信
回复
3天前
相关问题
JS如何添加日历日程提醒?
7999浏览 • 1回复 待解决
HarmonyOS 日历里面添加日历问题
67浏览 • 1回复 待解决
PA开发,如何添加日历提醒?
4117浏览 • 1回复 待解决
HarmonyOS 日历相关组件
462浏览 • 1回复 待解决
HarmonyOS 创建日历失败
39浏览 • 1回复 待解决
HarmonyOS 日历组件cjcalendar文档
19浏览 • 1回复 待解决
HarmonyOS日历组件吗?
461浏览 • 1回复 待解决
HarmonyOS 日历门票相关demo
41浏览 • 1回复 待解决
日历功能异常,getCalendar失败
496浏览 • 1回复 待解决
HarmonyOS CJCalendar 日历组件无法编译
927浏览 • 1回复 待解决
HarmonyOS 日历重复规则如何设置
46浏览 • 1回复 待解决
有没有调用日历接口?
6477浏览 • 1回复 待解决
HarmonyOS 月视图模式日历组件参考
90浏览 • 1回复 待解决
HarmonyOS 希望官方提供日历组件
335浏览 • 1回复 待解决
如何跳转到系统日历应用?
452浏览 • 1回复 待解决
动态申请权限能否添加描述
779浏览 • 1回复 待解决
如何让日历显示是农历日期?
899浏览 • 1回复 待解决
系统日历方法使用会抛异常
468浏览 • 0回复 待解决
HarmonyOS 日期/日历/时间选择器开发
549浏览 • 1回复 待解决