资讯专栏INFORMATION COLUMN

Cordova创建系统日历事件

snowLu / 986人阅读

摘要:在制作一款打卡的时候有这么一个需求创建提醒到系统日历中,也就是利用系统日历来做事件的提醒,这么做的好处很明显,无需处理提醒的细节,也无需后台。

在制作一款打卡App的时候有这么一个需求 -- 创建提醒到系统日历中,也就是利用系统日历来做事件的提醒,这么做的好处很明显,App无需处理提醒的细节,也无需后台。这个App是基于Cordova开发的,并没有访问系统日历的接口,我们只能通过插件来完成,这是一个有趣的挑战。

APP设计

请看下图,App允许创建事项时,可以设置重复,开始,结束和提醒时间四个选项:

这四个选项对创建到日历的事件都有影响:

重复 可以设置一周中的任意几天,比如选择周一到周五表示只要工作日。

开始 从哪天天开始

结束 到哪天结束

提醒时间 在每天的哪个时间发出提醒

这个四个组合起来就构成一个日历事件。

插件

Cordova平台实际上是一个基于web的平台,所以除了webview提供的能力,其他和设备交互的功能全部依赖于插件来完成,插件的安装和使用通常并不困难,比如增加一个关于状态栏控制的插件,可以在项目下这么做:

cordova plugin add cordova-plugin-statusbar

然后在js里调用插件提供的接口就可以了,更多的关于cordova平台和插件的使用,我有一个视频课程可以参考。很明显,创建系统日历事件也需要通过插件来做,搜索之后我们可以发现,完成这个功能的插件并不多,其中使用比较多的是cordova-plugin-calendar,试着安装

cordova plugin add cordova-plugin-calendar

这个插件可以支持android和iOS,我们现在android下测试,首先在js里写下下面的代码:

let calOptions = window.plugins.calendar.getCalendarOptions()
calOptions.firstReminderMinutes = 0
calOptions.secondReminderMinutes = null
calOptions.recurrenceEndDate = actionRemindEnd(action)
if (action.repeat.length === 7) {
  calOptions.recurrence = "daily"
}
else {
  calOptions.recurrence = "weekly"
  calOptions.recurrenceByDay = dateRepeat2Calendar(action.repeat)
}
window.plugins.calendar.createEventWithOptions(
  action.name, null, "dayday", eventTime, new Date(eventTime.getTime() + 15 * 60000), calOptions,
  (result) => {
  }, (err) => {
  })

action保存了用户所创建的一个活动事件的所有信息,其中有两个函数就不展开了,看起来应该可以了,实测的结果却是,日历事件创建起来了,没有报错,但是重复有问题,并没有能一直重复下去,在重复数次之后,事件就停了,类似下图这样,到15号事件就没有了:

修改插件

在这种情况下,调试js代码已经没有什么帮助了,js代码已经完全按照插件的要求来传递了参数,只能打开android studio,加载cordova项目下platforms/android下的这个工程,这个工程就是一个标准的android项目,打开之后可以定位到这个插件所提供的源码文件,找到AbstractCalendarAccessor.java,其中的createEvent函数完成在android下创建一个日历事件所做的事情,代码如下:

public String createEvent(Uri eventsUri, String title, long startTime, long endTime, String description,
                              String location, Long firstReminderMinutes, Long secondReminderMinutes,
                              String recurrence, int recurrenceInterval, String recurrenceWeekstart,
                              String recurrenceByDay, String recurrenceByMonthDay, Long recurrenceEndTime, Long recurrenceCount,
                              String allday,
                              Integer calendarId, String url) {
        ContentResolver cr = this.cordova.getActivity().getContentResolver();
        ContentValues values = new ContentValues();
        final boolean allDayEvent = "true".equals(allday) && isAllDayEvent(new Date(startTime), new Date(endTime));
        if (allDayEvent) {
            //all day events must be in UTC time zone per Android specification, getOffset accounts for daylight savings time
            values.put(Events.EVENT_TIMEZONE, "UTC");
            values.put(Events.DTSTART, startTime + TimeZone.getDefault().getOffset(startTime));
            values.put(Events.DTEND, endTime + TimeZone.getDefault().getOffset(endTime));
        } else {
            values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            values.put(Events.DTSTART, startTime);
            values.put(Events.DTEND, endTime);
        }
        values.put(Events.ALL_DAY, allDayEvent ? 1 : 0);
        values.put(Events.TITLE, title);
        // there"s no separate url field, so adding it to the notes
        if (url != null) {
            if (description == null) {
                description = url;
            } else {
                description += " " + url;
            }
        }
        values.put(Events.DESCRIPTION, description);
        values.put(Events.HAS_ALARM, firstReminderMinutes > -1 || secondReminderMinutes > -1 ? 1 : 0);
        values.put(Events.CALENDAR_ID, calendarId);
        values.put(Events.EVENT_LOCATION, location);

        if (recurrence != null) {
            String rrule = "FREQ=" + recurrence.toUpperCase() +
                    ((recurrenceInterval > -1) ? ";INTERVAL=" + recurrenceInterval : "") +
                    ((recurrenceWeekstart != null) ? ";WKST=" + recurrenceWeekstart : "") +
                    ((recurrenceByDay != null) ? ";BYDAY=" + recurrenceByDay : "") +
                    ((recurrenceByMonthDay != null) ? ";BYMONTHDAY=" + recurrenceByMonthDay : "") +
                    ((recurrenceEndTime > -1) ? ";UNTIL=" + nl.xservices.plugins.Calendar.formatICalDateTime(new Date(recurrenceEndTime)) : "") +
                    ((recurrenceCount > -1) ? ";COUNT=" + recurrenceCount : "");
            values.put(Events.RRULE, rrule);
        }

        String createdEventID = null;
        try {
            Uri uri = cr.insert(eventsUri, values);
            createdEventID = uri.getLastPathSegment();
            Log.d(LOG_TAG, "Created event with ID " + createdEventID);

            if (firstReminderMinutes > -1) {
                ContentValues reminderValues = new ContentValues();
                reminderValues.put("event_id", Long.parseLong(uri.getLastPathSegment()));
                reminderValues.put("minutes", firstReminderMinutes);
                reminderValues.put("method", 1);
                cr.insert(Uri.parse(CONTENT_PROVIDER + CONTENT_PROVIDER_PATH_REMINDERS), reminderValues);
            }

            if (secondReminderMinutes > -1) {
                ContentValues reminderValues = new ContentValues();
                reminderValues.put("event_id", Long.parseLong(uri.getLastPathSegment()));
                reminderValues.put("minutes", secondReminderMinutes);
                reminderValues.put("method", 1);
                cr.insert(Uri.parse(CONTENT_PROVIDER + CONTENT_PROVIDER_PATH_REMINDERS), reminderValues);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Creating reminders failed, ignoring since the event was created.", e);
        }
        return createdEventID;
    }

这段代码并不长,在Android Studio下设置断点,连接真机调试,发现整个过程没有任何错误,日历事件已经创建起来,但就是重复次数不正确。好吧,找到android api参考,看看官方文档中怎么说的:

Here are the rules for inserting a new event:

You must include CALENDAR_ID and DTSTART.

You must include an EVENT_TIMEZONE. To get a list of the system"s installed time zone IDs, use getAvailableIDs(). Note that this rule does not apply if you"re inserting an event through the INSERT Intent, described in Using an intent to insert an event—in that scenario, a default time zone is supplied.

For non-recurring events, you must include DTEND.

For recurring events, you must include a DURATION in addition to RRULE or RDATE. Note that this rule does not apply if you"re inserting an event through the INSERT Intent, described in Using an intent to insert an event—in that scenario, you can use an RRULE in conjunction with DTSTART and DTEND, and the Calendar application converts it to a duration automatically.

仔细对照代码和文档,我们发现DURATION这个参数并没有按照文档来传递,好吧,我们修改一下关键代码:

if (allDayEvent) {
  //all day events must be in UTC time zone per Android specification, getOffset accounts for daylight savings time
  values.put(Events.EVENT_TIMEZONE, "UTC");
  values.put(Events.DTSTART, startTime + TimeZone.getDefault().getOffset(startTime));
  if (recurrence == null) {
    values.put(Events.DTEND, endTime + TimeZone.getDefault().getOffset(endTime));
  } else {
    values.put(Events.DURATION, "P" + ((endTime - startTime) / (24 * 60 * 60000)) + "D");
  }
} else {
  values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
  values.put(Events.DTSTART, startTime);
  if (recurrence == null) {
    values.put(Events.DTEND, endTime);
  } else {
    values.put(Events.DURATION, "P" + ((endTime - startTime) / 60000) + "M");
  }
}

修改后的代码再次测试,这次ok了,这个例子表明了cordova生态的一个现象,插件质量参差不齐,有些插件可能需要我们的修改才能工作。

应用修改

为了使用修改后的插件,我们可以删除原来的插件,使用fork并修改后的插件,很简单,方法如下:

cordova plugin remove cordova-plugin-calendar
cordova plugin add https://github.com/i38/Calendar-PhoneGap-Plugin.git

所有其他代码都不用修改,这是cordova很灵活的一个地方,这样一切都ok了,最后附上完整App的链接,有兴趣可以参考: 天天。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/99841.html

相关文章

  • cordova研习笔记(二) —— cordova 6.X 源码解读(上)

    摘要:本文源码为版本。的代码结构也是一个很经典的定义结构构造函数实例修改函数原型共享实例方法,它提供事件通道上事件的订阅撤消订阅调用。 前言 cordova(PhoneGap) 是一个优秀的经典的中间件框架,网上对其源代码解读的文章确实不多,本系列文章试着解读一下,以便对cordova 框架的原理理解得更深入。本文源码为cordova android版本6.1.2。 源码结构 我们使用IDE...

    Java_oldboy 评论0 收藏0
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo

    摘要:经过网上查找很多资料,发现很多只有的项目整合,但是使用插件的文章很少,现在把从创建和创建到使用插件到项目打包到手机运行过程记录下来先上项目结构目录项目创建安装环境这个这边就不描述了,网上很多教程创建应用创建项目为目录命名空间项目名称添加平台 经过网上查找很多资料,发现很多只有vue+cordova的项目整合,但是vue使用cordova插件的文章很少,现在把从创建cordova和创建v...

    zhonghanwen 评论0 收藏0
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo

    摘要:经过网上查找很多资料,发现很多只有的项目整合,但是使用插件的文章很少,现在把从创建和创建到使用插件到项目打包到手机运行过程记录下来先上项目结构目录项目创建安装环境这个这边就不描述了,网上很多教程创建应用创建项目为目录命名空间项目名称添加平台 经过网上查找很多资料,发现很多只有vue+cordova的项目整合,但是vue使用cordova插件的文章很少,现在把从创建cordova和创建v...

    QiuyueZhong 评论0 收藏0
  • cordova研习笔记(一) —— 初试牛刀之cordova.js概要

    摘要:任何初始化任务应该在文件中的事件的事件处理函数中。这个配置文件有几个地方很关键,一开始没有认真看,将插件导进工程跑的时候各种问题,十分头痛,不得不重新认真看看文档。 前言 来新公司的第一个任务,研究hybrid App中间层实现原理,做中间层插件开发。这个任务挺有意思,也很有挑战性,之前在DCloud虽然做过5+ App开发,但是中间层的东西确实涉及不多。本系列文章属于系列开篇cord...

    buildupchao 评论0 收藏0

发表评论

0条评论

snowLu

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<