添加系统日历事件

前两天,产品提一个需求,说是弄一个系统日历的提醒,到时提醒用户做一些事情,大概这么一个需求。搞了一两天,查看API翻阅文档,算是完成需求了。
这篇文章一个纯粹的代码文章,就是告诉怎么用系统日历添加提醒,跟大家分享一下,以后可以直接拿过来用。
上代码:

CalendarHelper##

package com.example.asia.canlendartest;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.widget.Toast;
import java.util.ArrayList;import java.util.TimeZone;

public class CalendarHelper {
    private static final int QUERY = 1;
    private static final int INSERT = 2;
    private Context mContext;
    private MyAsyncQueryHandler mAsyncQueryHandler;
    private ArrayList aList = new ArrayList();
    private int insertCount;//一次性添加日历事件的个数
    private int insertCompleteCount;//当天添加的第几个日历事件
    private OnCalendarQueryCompleteListener onCalendarQueryComplete;
    private ArrayList titleArrayList = new ArrayList();
    private static final String ERROR_PERMISSION = "请到【设置】检查,日历权限是否打开。";
    public CalendarHelper(Context context){
        this.mContext = context;
        mAsyncQueryHandler = new MyAsyncQueryHandler(mContext.getContentResolver());
    } 
   /**
     * 查询添加的日历事件
     * @param titles
     */
    public void queryTitlesEvent(ArrayList titles){
        if(!hasCalendarPermission()){
            Toast.makeText(mContext, ERROR_PERMISSION, Toast.LENGTH_SHORT).show(); 
           return;
        }
        int size = titles.size();
        if(size == 0){
            return;
        }
        Uri eventUri = Uri.parse("content://com.android.calendar/events");
        /*if(Build.VERSION.SDK_INT>=14){
            eventUri =  Events.CONTENT_URI;
        }else {
            eventUri =  Uri.parse("content://com.android.calendar/events");
        }*/
        String[] strs = new String[size];
        //deleted=0表示该日历事件未删除,deleted=1表示该日历事件已删除
        mAsyncQueryHandler.startQuery( QUERY,  null, eventUri, new String[]{"title"}, "title IN ("+getStrAry(size)+")" + " and " + "deleted=0", titles.toArray(strs), null);
    } 
   /**
     *  当查询日历完成后调用,用来看看是否已经成功添加到系统中了
     * @param token
     * @param cookie
     * @param cursor
     */
    private  void  onCalendarQueryComplete(int token, Object cookie, Cursor cursor){
        try{
            while(cursor.moveToNext()){
                aList.add(cursor.getString(cursor.getColumnIndex("title")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor != null){
                cursor.close();
            }
            if(onCalendarQueryComplete != null ){
                onCalendarQueryComplete.onQueryComplete(aList);
            }
        }
    }
    /**
     * 添加日历事件
     * @param calendarEvents
     * @param onCalendarQueryCompleteListener
     */    public void insertEvent2Calendar(ArrayList calendarEvents, OnCalendarQueryCompleteListener onCalendarQueryCompleteListener){
        if(!hasCalendarPermission()){
            Toast.makeText(mContext, ERROR_PERMISSION, Toast.LENGTH_SHORT).show();
            return;
        }
        this.onCalendarQueryComplete = onCalendarQueryCompleteListener;
        insertCount = calendarEvents.size();
        String eventUriString = "content://com.android.calendar/events";
        for (int i = 0; i < insertCount; i++) { 
           ContentValues values = new ContentValues();
            CalendarEvent c = calendarEvents.get(i); 
           titleArrayList.add(c.getTitleString());
            values.put("calendar_id", 1);
            values.put("title", c.getTitleString()); 
           values.put("description",  c.getDescription()); 
           values.put("dtstart", c.getStartTimeInMillis());
            values.put("dtend", c.getEndTimeInMillis());
            values.put("eventTimezone", TimeZone.getDefault().getID());
            values.put("hasAlarm", 1); 
           try {
                mAsyncQueryHandler.startInsert(c.getMinutes(), c.isNeedReminder(), Uri.parse(eventUriString), values);
            } catch (Exception e) { 
               e.printStackTrace(); 
           }
        } 
   } 
   private void onCalendarInsertComplete(int minutes, Object needRemind, Uri eventUri) {
       insertCompleteCount ++;
        if(eventUri == null){
            if(insertCompleteCount == 1){ 
               Toast.makeText(mContext, ERROR_PERMISSION, Toast.LENGTH_SHORT).show();
            }
            return;
        } 
       if((Boolean)needRemind){
            ContentValues values = new ContentValues();
            String reminderUriString = "content://com.android.calendar/reminders";
            long eventID = Long.parseLong(eventUri.getLastPathSegment()); 
           values.put("event_id", eventID);
            values.put("minutes", minutes);
            values.put("method", 1); 
  

            try {
                mAsyncQueryHandler.startInsert(0, false, Uri.parse(reminderUriString), values);
            } catch (Exception e) {
                e.printStackTrace();
            } 
       } 
       if(insertCompleteCount == insertCount && onCalendarQueryComplete != null){
            queryTitlesEvent(titleArrayList);
        }
    }

    private  class MyAsyncQueryHandler  extends AsyncQueryHandler {
        public MyAsyncQueryHandler(ContentResolver cr) { 
           super(cr);
        }
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            onCalendarQueryComplete(token, cookie, cursor);
            super.onQueryComplete(token, cookie, cursor);
        }
        @Override
        protected void onInsertComplete(int token, Object cookie, Uri uri) {
            onCalendarInsertComplete(token, cookie, uri);
            super.onInsertComplete(token, cookie, uri);
        }
    }
    public void setOnCalendarQueryComplete(OnCalendarQueryCompleteListener onCalendarQueryComplete){        this.onCalendarQueryComplete = onCalendarQueryComplete;
    }
    public interface OnCalendarQueryCompleteListener{
        void onQueryComplete(ArrayList insertSuccess);
    }
    //String title, String description,  long startTimeInMillis, long endTimeInMillis, Boolean needReminder, Integer minutes    public class CalendarEvent {
        private String titleString;//添加的日历事件名称
        private String description;//日历事件名称的描述
        private long startTimeInMillis;//日历开始时间毫秒值
        private long endTimeInMillis;//日历结束时间毫秒值
        private boolean needReminder;//是否需要闹铃提醒
        private int minutes;//日历开始时间提前多久提醒
        public CalendarEvent(String titleString, String description,
                             long startTimeInMillis, long endTimeInMillis,
                             boolean needReminder, int minutes) {
            super();
            this.titleString = titleString;
            this.description = description;
            this.startTimeInMillis = startTimeInMillis;
            this.endTimeInMillis = endTimeInMillis;
            this.needReminder = needReminder;
            this.minutes = minutes;
        }
        public String getTitleString() { 
           return titleString;
        } 
       public void setTitleString(String titleString) {
            this.titleString = titleString;
        } 
       public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        } 
       public long getStartTimeInMillis() {
            return startTimeInMillis;
        } 
       public void setStartTimeInMillis(long startTimeInMillis) {
            this.startTimeInMillis = startTimeInMillis;
        } 
       public long getEndTimeInMillis() { 
           return endTimeInMillis;
        }
        public void setEndTimeInMillis(long endTimeInMillis) {
            this.endTimeInMillis = endTimeInMillis;
        }
        public boolean isNeedReminder() {
            return needReminder;
        }
        public void setNeedReminder(boolean needReminder) {
            this.needReminder = needReminder;
        }
        public int getMinutes() {
            return minutes;
        }
        public void setMinutes(int minutes) {
            this.minutes = minutes;
        }
   }
    private String getStrAry(int amount){
        String string = "";
        for (int i = 0; i < amount; i++) {
            string = string + ( i== amount-1 ? "?" : "?,");
        }
        return string;
    }
    /**
     * 判断是否提供了修改日历内容的权限
     * @return
     */    private boolean hasCalendarPermission(){
        return PackageManager.PERMISSION_GRANTED == mContext.getPackageManager().checkPermission("android.permission.READ_CALENDAR", mContext.getPackageName());    }}

MainActivity中使用demo

package com.example.asia.canlendartest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;import android.view.View;
import android.widget.Toast;import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public  void insertEvent2Calendar(View view) {
        CalendarHelper calendarHelper = new CalendarHelper(this);
//String title, String description,  long startTimeInMillis, long endTimeInMillis, Boolean needReminder, Integer minutes
        final String title1 = "我是日历标题1";
        final String title2 = "我是日历标题2";
        //创建日历事件1
        CalendarHelper.CalendarEvent calendarEvent1 = calendarHelper.new CalendarEvent(
                title1, 
               "我是日历标题1的详细描述",
                Tools.date2Millis("2017-01-05-09-30-00", "yyyy-MM-dd-HH-mm-ss"), 
               Tools.date2Millis("2017-01-05-19-30-00", "yyyy-MM-dd-HH-mm-ss"),
                true, 0);
        //创建日历事件2
        CalendarHelper.CalendarEvent calendarEvent2 = calendarHelper.new CalendarEvent(
                title2, 
               "我是日历标题2的详细描述",
                Tools.date2Millis("2017-01-05-20-23-00", "yyyy-MM-dd-HH-mm-ss"),
                Tools.date2Millis("2017-01-05-21-10-00", "yyyy-MM-dd-HH-mm-ss"), 
               true, 0);
        ArrayList arrayList = new ArrayList();
        arrayList.add(calendarEvent1);
        arrayList.add(calendarEvent2);
        //将日历事件添加到系统日历中
        calendarHelper.insertEvent2Calendar(arrayList, new CalendarHelper.OnCalendarQueryCompleteListener() { 
           @Override
            public void onQueryComplete(ArrayList aList) {
                if(aList.contains(title1) || aList.contains(title2)){
                    Toast.makeText(MainActivity.this, "添加日历成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "添加日历失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Tools

public class Tools {
    /**
     * 日期转毫秒
     * @param dateStr
     * @param dateFormat
     * @return
     */
    public static long date2Millis(String dateStr, String dateFormat){ 
       SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        try{
            long millis = sdf.parse(dateStr).getTime();
            return millis;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
}

反正在我们现在的项目中没有什么问题,不过貌似对某些机型有兼容性问题,大概是测试给我的一个索尼的手机。没办法,舍小家为大家了。那个索尼的兼容性的bug修不好,就搁置了。。其他的手机暂时没发现什么问题。

添加系统日历事件_第1张图片
device-2017-01-05-202332.png
添加系统日历事件_第2张图片
device-2017-01-05-202341.png

你可能感兴趣的:(添加系统日历事件)