2019July15_日历事件添加、查询、删除

一 需求

  1. 动态添加当前应用事件
  2. 查询当前应用的事件,区别其他应用
  3. 删除当前应用指定事件

二 效果图

三 原理分析

  1. 要调用系统日历API,并申请权限,注意申请动态权限
  2. 为当前应用在日历中创建一个账户id,以id区分是不是当前应用的日历事件
  3. 以日历事件的标题来区分当前应用的不同事件,调用日历API实现增、查、删

四 主要代码

工具类调用日历功能

public class CalendarReminderUtils {

    private static String CALENDER_URL = "content://com.android.calendar/calendars";
    private static String CALENDER_EVENT_URL = "content://com.android.calendar/events";
    private static String CALENDER_REMINDER_URL = "content://com.android.calendar/reminders";

    private static String CALENDARS_ACCOUNT_NAME = "1730882045";
    private static String CALENDARS_ACCOUNT_TYPE = "com.android.bpj";

    /**
     * 检查是否已经添加了日历账户,如果没有添加先添加一个日历账户再查询
     * 获取账户成功返回账户id,否则返回-1
     */
    private static int checkAndAddCalendarAccount(Context context) {
        int oldId = checkCalendarAccount(context);
        if (oldId >= 0) {
            return oldId;
        } else {
            long addId = addCalendarAccount(context);
            if (addId >= 0) {
                return checkCalendarAccount(context);
            } else {
                return -1;
            }
        }
    }

    /**
     * 检查是否存在现有账户,存在则返回账户id,否则返回-1
     */
    private static int checkCalendarAccount(Context context) {
        Cursor userCursor = context.getContentResolver().query(Uri.parse(CALENDER_URL), null, null, null, null);
        try {
            if (userCursor == null) { //查询返回空值
                return -1;
            }
            int count = userCursor.getCount();
            if (count > 0) { //存在现有账户,取第一个账户的id返回
                for (userCursor.moveToFirst(); !userCursor.isAfterLast(); userCursor.moveToNext()) {
                    String accountName = userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME));
                    if (CALENDARS_ACCOUNT_NAME.equals(accountName)) {
                        return userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID));
                    }
                }
                return -1;
            } else {
                return -1;
            }
        } finally {
            if (userCursor != null) {
                userCursor.close();
            }
        }
    }

    /**
     * 添加日历账户,账户创建成功则返回账户id,否则返回-1
     */

    private static long addCalendarAccount(Context context) {
        TimeZone timeZone = TimeZone.getDefault();
        ContentValues value = new ContentValues();
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME);
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE);
        value.put(CalendarContract.Calendars.VISIBLE, 1);
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
        value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, CALENDARS_ACCOUNT_NAME);
        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri calendarUri = Uri.parse(CALENDER_URL);
        calendarUri = calendarUri.buildUpon()
                .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE)
                .build();

        Uri result = context.getContentResolver().insert(calendarUri, value);
        long id = result == null ? -1 : ContentUris.parseId(result);
        return id;
    }



    /**
     * 添加日历事件
     */
    public static void addCalendarEvent(Context context, String title, String description, long reminderTime, int previousDate) {
        if (context == null) {
            return;
        }
        int calId = checkAndAddCalendarAccount(context); //获取日历账户的id
        if (calId < 0) { //获取账户id失败直接返回,添加日历事件失败
            return;
        }
        //添加日历事件
        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(reminderTime);//设置开始时间
        long start = mCalendar.getTime().getTime();
        mCalendar.setTimeInMillis(start + 10 * 60 * 1000);//设置终止时间,开始时间加10分钟
        long end = mCalendar.getTime().getTime();
        ContentValues event = new ContentValues();
        event.put(CalendarContract.Events.TITLE, title );
        event.put(CalendarContract.Events.DESCRIPTION, description);
        event.put(CalendarContract.Events.CALENDAR_ID, calId); //插入账户的id
        event.put(CalendarContract.Events.DTSTART, start);

        event.put(CalendarContract.Events.DTEND, end);
        event.put(CalendarContract.Events.HAS_ALARM, 1);//设置有闹钟提醒
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Beijing");//这个是时区,必须有
        Uri newEvent = context.getContentResolver().insert(Uri.parse(CALENDER_EVENT_URL), event); //添加事件
        if (newEvent == null) { //添加日历事件失败直接返回
            return;
        }

        //事件提醒的设定
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent));
        values.put(CalendarContract.Reminders.MINUTES, previousDate * 24 * 60);// 提前previousDate天有提醒
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
        Uri uri = context.getContentResolver().insert(Uri.parse(CALENDER_REMINDER_URL), values);
        if (uri == null) { //添加事件提醒失败直接返回
            return;
        }
    }

    public static List> query(Context context) {
        Cursor eventCursor = context.getContentResolver().query(Uri.parse(CALENDER_EVENT_URL), null, null, null, null);
        List> list = new ArrayList<>();
        try {
            if (eventCursor == null) { //查询返回空值
                return list;
            }
            int accountId = checkCalendarAccount(context);
            if (eventCursor.getCount() > 0 && accountId > 0) {
                //遍历所有事件,找到title跟需要查询的title一样的项
                for (eventCursor.moveToFirst(); !eventCursor.isAfterLast(); eventCursor.moveToNext()) {
                    int calId = eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Events.CALENDAR_ID));
                    if (accountId == calId) {
                        Map map = new HashMap<>();
                        map.put(CalendarContract.Events.TITLE, eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.TITLE)));
                        map.put(CalendarContract.Events.DESCRIPTION, eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.DESCRIPTION)));
                        list.add(map);
                    }
                }
            }
        } finally {
            if (eventCursor != null) {
                eventCursor.close();
            }
        }


        return list;
    }


    /**
     * 删除日历事件
     */
    public static void deleteCalendarEvent(Context context, String title) {
        if (context == null) {
            return;
        }
        Cursor eventCursor = context.getContentResolver().query(Uri.parse(CALENDER_EVENT_URL), null, null, null, null);
        try {
            if (eventCursor == null) { //查询返回空值
                return;
            }
            if (eventCursor.getCount() > 0) {
                //遍历所有事件,找到title跟需要查询的title一样的项
                for (eventCursor.moveToFirst(); !eventCursor.isAfterLast(); eventCursor.moveToNext()) {
                    String eventTitle = eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.TITLE));
                    if (!TextUtils.isEmpty(title) && (title).equals(eventTitle)) {
                        int id = eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Calendars._ID));//取得id
                        Uri deleteUri = ContentUris.withAppendedId(Uri.parse(CALENDER_EVENT_URL), id);
                        int rows = context.getContentResolver().delete(deleteUri, null, null);
                        if (rows == -1) { //事件删除失败
                            return;
                        }
                    }
                }
            }
        } finally {
            if (eventCursor != null) {
                eventCursor.close();
            }
        }
    }
}

使用

 private ListView lv;
    private String[] permissions = new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public int x = 0, y = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_activity);
        checkPermission();
    }

    private boolean checkPermission() {
        String[] perms = AppUtils.getDeniedPermissions(this, permissions);
        if (perms == null || perms.length == 0) {
            return true;
        } else {
            AppUtils.requestPermissions(this, permissions, PermissionActivity.CODE_PERMISSION_REQUEST);
            return false;
        }
    }

    public void add(View v) {
        Calendar calendar = Calendar.getInstance();
        CalendarReminderUtils.addCalendarEvent(this, "标题" + x, "到期提醒" + x, calendar.getTimeInMillis(), 0);
        x++;
    }

    public void query(View v) {
        x = 0;
        y = 0;
        lv = (ListView) findViewById(R.id.lv);
        List> list = CalendarReminderUtils.query(this);
        lv.setAdapter(new ArrayAdapter>(this, android.R.layout.simple_dropdown_item_1line, list));
    }

    public void delete(View v) {
        CalendarReminderUtils.deleteCalendarEvent(this, "标题" + y);
        y++;
    }

注意添加权限(动态权限申请checkPermission):

  
  

4 Demo

CalendarActivity

你可能感兴趣的:(2019July15_日历事件添加、查询、删除)