首页 > 编程语言 >【Java UI】HarmonyOS添加日历事件

【Java UI】HarmonyOS添加日历事件

时间:2022-09-21 09:11:52浏览次数:105  
标签:Java EventsColumns System HarmonyOS UI ohos new valuesBucket String

参考资料

CalendarDataHelper

Events

Reminders

api讲解

添加权限

在config.json添加权限代码如下

 "reqPermissions": [
      {
        "name": "ohos.permission.READ_CALENDAR"
      },
      {
        "name": "ohos.permission.WRITE_CALENDAR"
      },
      {
        "name": "ohos.permission.PUBLISH_AGENT_REMINDER"
      }
    ]

在java代码动态注册权限

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        String[] permissions = {
                "ohos.permission.READ_CALENDAR",
                "ohos.permission.WRITE_CALENDAR",
                "ohos.permission.PUBLISH_AGENT_REMINDER"
        };
        requestPermissionsFromUser(permissions, 0);
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
    }
}
添加日历事件
    public void insert(Context context) {
        try {
            EventsHelper = CalendarDataHelper.creator(context, Events.class);
            //新增日历事件
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putInteger(EventsColumns.ACC_ID, 1);
            valuesBucket.putNull(EventsColumns.DURATION);
            valuesBucket.putString(EventsColumns.START_TIMEZONE, TimeZone.getDefault().getID());
            valuesBucket.putString(EventsColumns.EVENT_POSITION, "上海");
            valuesBucket.putString(EventsColumns.TITLE, "标题");
            valuesBucket.putString(EventsColumns.DESCRIPTION, "描述");
            valuesBucket.putLong(EventsColumns.EVENT_START_TIME, System.currentTimeMillis());
            valuesBucket.putLong(EventsColumns.EVENT_END_TIME, System.currentTimeMillis()+8*1000*60*60);
         boolean isok=   EventsHelper.insert(valuesBucket);
         System.err.println(isok?"####===>添加成功":"#####===>>添加失败");
        } catch (DataAbilityRemoteException e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
修改日历事件
  String PREDICTOR_TEMPLATE = "(%s)";
        String sq1 = String.format(
                Locale.ENGLISH,
                PREDICTOR_TEMPLATE,
                "calendar_id =" + 1);
        DataAbilityPredicates predicates = new DataAbilityPredicates(sq1);
        EventsHelper = CalendarDataHelper.creator(context, Events.class);
        //新增日历事件
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putInteger(EventsColumns.ACC_ID, 1);
        valuesBucket.putString(EventsColumns.TITLE, "修改标题");
        //修改日历事件
        boolean isupdate = EventsHelper.update(valuesBucket, predicates);
        if (isupdate) {
            System.err.println("#######====>修改成功");
        } else {
            System.err.println("#######====>修改失败");
        }
查询日历事件
  String PREDICTOR_TEMPLATE = "(%s)";
        String sq1 = String.format(
                Locale.ENGLISH,
                PREDICTOR_TEMPLATE,
                "calendar_id =" + 1);
        DataAbilityPredicates predicates = new DataAbilityPredicates(sq1);
        EventsHelper = CalendarDataHelper.creator(context, Events.class);
//查询日历事件
        String[] eventColumns = new String[]{
                Events.ID,
                EventsColumns.TITLE,
                EventsColumns.DESCRIPTION,
                EventsColumns.EVENT_START_TIME,
                EventsColumns.EVENT_END_TIME,
        };
        CalendarCollection calendarCollection = null;
        calendarCollection = EventsHelper.query(predicates, eventColumns);
    int id=-1;
        while (calendarCollection != null && calendarCollection.hasNext()) {
            Events resultEntity = (Events) calendarCollection.next()
                    .filter(entity -> entity instanceof Events)
                    .orElse(null);
            System.err.println("####====>>"+resultEntity.getTitle() + "=" + resultEntity.getDescription()+"="+resultEntity.getId());
                id=resultEntity.getId();
//            Optional.ofNullable(calendarCollection).ifPresent(CalendarCollection::close);
删除日历事件
  EventsHelper = CalendarDataHelper.creator(ability, Events.class);
        DataAbilityPredicates predicates = new DataAbilityPredicates("title like '%修改标题%'");
        int flag = EventsHelper.delete(predicates);
        System.err.println(flag > 0 ? "####===》删除成功" : "####===》删除失败");
添加日历提醒
        CalendarDataHelper      RemindersHelper = CalendarDataHelper.creator(context, Reminders.class);
        ValuesBucket reminderBucket = new ValuesBucket();
        reminderBucket.putInteger(RemindersColumns.EVENT_ID, id);
        reminderBucket.putInteger(RemindersColumns.REMIND_TYPE, RemindersColumns.TYPE_ALARM);
        reminderBucket.putInteger(RemindersColumns.REMIND_MINUTES, 1);
        reminderBucket.putInteger("method",1);
        boolean   isok= false;
        try {
            isok = RemindersHelper.insert(reminderBucket);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        System.err.println(isok?"###===>设置成功"+id:"#####====>>设置失败"+id);

 

 

运行效果

全部代码
xml布局
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">
    <Button
        ohos:height="80vp"
        ohos:width="match_parent"
        ohos:text="添加事件"
        ohos:text_size="20fp"
        ohos:id="$+id:insertEvent"/>
    <Button
        ohos:height="80vp"
        ohos:width="match_parent"
        ohos:text="修改事件"
        ohos:background_element="#ed6262"
        ohos:text_size="20fp"
        ohos:id="$+id:UpdateEvent"/>
    <Button
        ohos:height="80vp"
        ohos:width="match_parent"
        ohos:text="查询事件"
        ohos:text_size="20fp"
        ohos:id="$+id:selectEvent"/>
    <Button
        ohos:height="80vp"
        ohos:width="match_parent"
        ohos:text="设置提醒"
        ohos:background_element="#ed6262"
        ohos:text_size="20fp"
        ohos:id="$+id:setReminders"/>
    <Button
        ohos:height="80vp"
        ohos:width="match_parent"
        ohos:text="删除"
        ohos:text_size="20fp"
        ohos:id="$+id:deleteEvent"/>

</DirectionalLayout>

java代码

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.sysappcomponents.calendar.CalendarCollection;
import ohos.sysappcomponents.calendar.CalendarDataHelper;
import ohos.sysappcomponents.calendar.column.EventsColumns;
import ohos.sysappcomponents.calendar.column.RemindersColumns;
import ohos.sysappcomponents.calendar.entity.Events;
import ohos.sysappcomponents.calendar.entity.Reminders;

import java.util.Locale;
import java.util.TimeZone;

public class MainAbilitySlice extends AbilitySlice {
    private CalendarDataHelper  EventsHelper = CalendarDataHelper.creator(this, Events.class);
    private int id;
    CalendarDataHelper      RemindersHelper = CalendarDataHelper.creator(this, Reminders.class);
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        findComponentById(ResourceTable.Id_insertEvent).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    //新增日历事件
                    ValuesBucket valuesBucket = new ValuesBucket();
                    valuesBucket.putInteger(EventsColumns.ACC_ID, 1);
                    valuesBucket.putNull(EventsColumns.DURATION);
                    valuesBucket.putString(EventsColumns.START_TIMEZONE, TimeZone.getDefault().getID());
                    valuesBucket.putString(EventsColumns.EVENT_POSITION, "上海");
                    valuesBucket.putString(EventsColumns.TITLE, "标题");
                    valuesBucket.putString(EventsColumns.DESCRIPTION, "描述");
                    valuesBucket.putLong(EventsColumns.EVENT_START_TIME, System.currentTimeMillis());
                    valuesBucket.putLong(EventsColumns.EVENT_END_TIME, System.currentTimeMillis()+8*1000*60*60);
                    boolean isok=   EventsHelper.insert(valuesBucket);
                    System.err.println(isok?"####===>添加成功":"#####===>>添加失败");
                } catch (DataAbilityRemoteException e) {
                    System.out.println(e.toString());
                    e.printStackTrace();
                }
            }
        });
        findComponentById(ResourceTable.Id_UpdateEvent).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    String PREDICTOR_TEMPLATE = "(%s)";
                    String sq1 = String.format(
                            Locale.ENGLISH,
                            PREDICTOR_TEMPLATE,
                            "calendar_id =" + 1);
                    DataAbilityPredicates predicates = new DataAbilityPredicates(sq1);
                    //新增日历事件
                    ValuesBucket valuesBucket = new ValuesBucket();
                    valuesBucket.putInteger(EventsColumns.ACC_ID, 1);
                    valuesBucket.putString(EventsColumns.TITLE, "修改标题");
                    //修改日历事件
                    boolean isupdate = EventsHelper.update(valuesBucket, predicates);
                    if (isupdate) {
                        System.err.println("#######====>修改成功");
                    } else {
                        System.err.println("#######====>修改失败");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    System.err.println("######====>"+e.getMessage());
                }

            }
        });

        findComponentById(ResourceTable.Id_selectEvent).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    String PREDICTOR_TEMPLATE = "(%s)";
                    String sq1 = String.format(
                            Locale.ENGLISH,
                            PREDICTOR_TEMPLATE,
                            "calendar_id =" + 1);
                    DataAbilityPredicates predicates = new DataAbilityPredicates(sq1);
                    //新增日历事件
//查询日历事件
                    String[] eventColumns = new String[]{
                            Events.ID,
                            EventsColumns.TITLE,
                            EventsColumns.DESCRIPTION,
                            EventsColumns.EVENT_START_TIME,
                            EventsColumns.EVENT_END_TIME,
                    };
                    CalendarCollection calendarCollection = null;
                    calendarCollection = EventsHelper.query(predicates, eventColumns);
                    while (calendarCollection != null && calendarCollection.hasNext()) {
                        Events resultEntity = (Events) calendarCollection.next()
                                .filter(entity -> entity instanceof Events)
                                .orElse(null);
                        System.err.println("####====>>"+resultEntity.getTitle() + "=" + resultEntity.getDescription()+"="+resultEntity.getId());
                        id=resultEntity.getId();
//            Optional.ofNullable(calendarCollection).ifPresent(CalendarCollection::close);

                    }

                } catch (DataAbilityRemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        findComponentById(ResourceTable.Id_deleteEvent).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    DataAbilityPredicates predicates = new DataAbilityPredicates("title like '%修改标题%'");
                    int flag = EventsHelper.delete(predicates);
                    System.err.println(flag > 0 ? "####===》删除成功" : "####===》删除失败");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        findComponentById(ResourceTable.Id_setReminders).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {


                ValuesBucket reminderBucket = new ValuesBucket();
                reminderBucket.putInteger(RemindersColumns.EVENT_ID, id);
                reminderBucket.putInteger(RemindersColumns.REMIND_TYPE, RemindersColumns.TYPE_ALARM);
                reminderBucket.putInteger(RemindersColumns.REMIND_MINUTES, 1);
                reminderBucket.putInteger("method",1);
                boolean   isok= false;
                try {
                    isok = RemindersHelper.insert(reminderBucket);
                } catch (DataAbilityRemoteException e) {
                    e.printStackTrace();
                }
                System.err.println(isok?"###===>设置成功"+id:"#####====>>设置失败"+id);
            }
        });

    }

}
运行效果

b2580c004705f0d24e5f5e74e0427082_1455x995.gif%40900-0-90-f.gif

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

标签:Java,EventsColumns,System,HarmonyOS,UI,ohos,new,valuesBucket,String
From: https://www.cnblogs.com/developer-huawei/p/16714382.html

相关文章

  • JAVA进阶--XML、XML解析、XPath、设计模式--2022年9月19日
    第一节1、XML是什么?XML的全称为(EXtensibleMarkupLanguage),是一种可扩展的标记语言它是一种数据表示格式,可以用于自定义数据格式2、......
  • HarmonyOS应用开发-声明式UI描述规范
    1.无构造参数配置组件的接口定义不包含必选构造参数,组件后面的“()”中不需要配置任何内容。示例:Column(){Text('item1')Divider()//Noparameterconfiguratio......
  • Java第一课
    一、java的运行假设有一个文件为HelloWorld.java运行java的过程为1、执行命令:javacHelloWorld.java这里javac是java编译器,将文件HelloWorld.java编译成HelloWorld.cla......
  • Java【Mybatis】——创建Mybatis Mapper模板
    目的在编码过程中,我们常常需要写一些配置文件。而这些配置文件的格式都是固定的——关键是我通常记不住,也是找地方复制。这种方法可以,但没有必要。因为一种方式,更简便—......
  • JavaWeb-SMBMS项目
    JavaWeb-SMBMS项目:学习视频-狂神说JavaWeb:视频链接JavaWeb-SMBMS项目一、SMBMSSMBMS模块数据库架构项目如何搭建?考虑是不是用maven?jar包,依赖二、项目搭建准备......
  • Java软件结构与数据结构 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1-aD4I1Fy1Q2j0DGbu-44ig点击这里获取提取码 ......
  • java方法
    java方法了解方法定义方法相当于函数System.out.println()//System:类,out:对象,println:方法  方法的定义及调用方法定义:   实际参数:实际调用给的值。形......
  • Java特种兵 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/16vbCmhnzgRtRVwrrh4bN1A点击这里获取提取码 ......
  • Java无难事:详解Java编程核心思想与技术 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1Ht352zrCXy9ArE-Th9fgNg点击这里获取提取码 ......
  • java日常遇到的异常
    空指针用到了为Null的数据文件找不到异常newFile时的路径参数不正确会报NoSuchFile类型转换异常实例化异常java.lang.InstantiationException获取到类的cl......