添加系統(tǒng)日歷事件

前兩天,產(chǎn)品提一個需求,說是弄一個系統(tǒng)日歷的提醒,到時提醒用戶做一些事情,大概這么一個需求。搞了一兩天,查看API翻閱文檔,算是完成需求了。
這篇文章一個純粹的代碼文章,就是告訴怎么用系統(tǒng)日歷添加提醒,跟大家分享一下,以后可以直接拿過來用。
上代碼:

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<String> aList = new ArrayList<String>();
    private int insertCount;//一次性添加日歷事件的個數(shù)
    private int insertCompleteCount;//當(dāng)天添加的第幾個日歷事件
    private OnCalendarQueryCompleteListener onCalendarQueryComplete;
    private ArrayList<String> titleArrayList = new ArrayList<String>();
    private static final String ERROR_PERMISSION = "請到【設(shè)置】檢查,日歷權(quán)限是否打開。";
    public CalendarHelper(Context context){
        this.mContext = context;
        mAsyncQueryHandler = new MyAsyncQueryHandler(mContext.getContentResolver());
    } 
   /**
     * 查詢添加的日歷事件
     * @param titles
     */
    public void queryTitlesEvent(ArrayList<String> 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);
    } 
   /**
     *  當(dāng)查詢?nèi)諝v完成后調(diào)用,用來看看是否已經(jīng)成功添加到系統(tǒng)中了
     * @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<CalendarEvent> 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<String> 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;//日歷結(jié)束時間毫秒值
        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;
    }
    /**
     * 判斷是否提供了修改日歷內(nèi)容的權(quán)限
     * @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 = "我是日歷標(biāo)題1";
        final String title2 = "我是日歷標(biāo)題2";
        //創(chuàng)建日歷事件1
        CalendarHelper.CalendarEvent calendarEvent1 = calendarHelper.new CalendarEvent(
                title1, 
               "我是日歷標(biāo)題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);
        //創(chuàng)建日歷事件2
        CalendarHelper.CalendarEvent calendarEvent2 = calendarHelper.new CalendarEvent(
                title2, 
               "我是日歷標(biāo)題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<CalendarHelper.CalendarEvent> arrayList = new ArrayList<CalendarHelper.CalendarEvent>();
        arrayList.add(calendarEvent1);
        arrayList.add(calendarEvent2);
        //將日歷事件添加到系統(tǒng)日歷中
        calendarHelper.insertEvent2Calendar(arrayList, new CalendarHelper.OnCalendarQueryCompleteListener() { 
           @Override
            public void onQueryComplete(ArrayList<String> 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 {
    /**
     * 日期轉(zhuǎn)毫秒
     * @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;
        }
    }
}

反正在我們現(xiàn)在的項目中沒有什么問題,不過貌似對某些機型有兼容性問題,大概是測試給我的一個索尼的手機。沒辦法,舍小家為大家了。那個索尼的兼容性的bug修不好,就擱置了。。其他的手機暫時沒發(fā)現(xiàn)什么問題。

device-2017-01-05-202332.png
device-2017-01-05-202341.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評論 25 708
  • 昨天下班路上,自行車胎突然爆掉了,沒辦法,只能推著去接娃,然后又推著回家,LG下班就就讓他推去修了。知道的家附近...
    云沐媽媽閱讀 354評論 0 0
  • “我們分手吧?!彼恼f?!澳愦_定?”電話那頭他有些不耐煩的反問道?!班?,確定,分手吧”這次沒有參雜一點點情...
    W九閱讀 253評論 0 0

友情鏈接更多精彩內(nèi)容