phonegap之android原生日历调用

  • android日历调用首先第一步我们要添加权限
  <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
  • 接着我们书写js调用接口
var calendar = {
        add: function (success, data) {
            exec(success, null, "Calendar", "add", [data]);
        },
        open:function(success, data){
            exec(success, null, "Calendar", "open", [data]);
        }

    };


    module.exports = calendar;
  • 这两个方法一个add是后台添加到日历数据库,一个打开日历,然后调用系统日历添加

由于android存在版本兼容我们要添加

if (Build.VERSION.SDK_INT >=8) {
                calanderURL = "content://com.android.calendar/calendars";
                calanderEventURL = "content://com.android.calendar/events";
                calanderRemiderURL = "content://com.android.calendar/reminders";

            } else {
                calanderURL = "content://calendar/calendars";
                calanderEventURL = "content://calendar/events";
                calanderRemiderURL = "content://calendar/reminders";
            }
  • android的日历存储有多个用户,但是系统默认一般会第一个
Cursor userCursor = cordova.getActivity().getContentResolver()
                    .query(Uri.parse(calanderURL), null, null, null, null);
            if (userCursor.getCount() > 0) {
                userCursor.moveToFirst();
                calId = userCursor.getString(userCursor.getColumnIndex("_id"));
            }
  • android后台添加日历参数,这个时候我们一般调用phonegap线程写法,不会影响ui
private void Add(final JSONObject sData, final CallbackContext context) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    ContentValues event = new ContentValues();
                    Log.v(TAG, sData.getString("dtstart"));
                    event.put("calendar_id", calId);
                    event.put(Events.TITLE, sData.getString("title"));
                    event.put(Events.EVENT_LOCATION,
                            sData.getString("location"));
                    event.put(Events.DESCRIPTION,
                            sData.getString("description"));
                    event.put(Events.DTSTART, sData.getLong("dtstart"));
                    event.put(Events.DTEND, sData.getLong("dtend"));
                    event.put("eventTimezone", TimeZone.getDefault().getID());
                    Uri url = cordova.getActivity().getContentResolver()
                            .insert(Uri.parse(calanderEventURL), event);
                    long id = Long.parseLong(url.getLastPathSegment());
                    ContentValues values = new ContentValues();
                    values.put("event_id", id);
                    // 提前10分钟有提醒
                    values.put("minutes", 10);
                    values.put("method", 1);
                    cordova.getActivity().getContentResolver()
                            .insert(Uri.parse(calanderRemiderURL), values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                context.success(); // Thread-safe.
            }
        });
    }
  • 如何调用android弹出系统添加页面了
private void Open() {
        Uri uri = Uri.parse(calanderEventURL);
        Intent intent = new Intent("android.intent.action.INSERT", uri);
        lastId = GetLastId();
        cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
        
    }
  • 因为调用系统添加日历我们无法知道我们添加的状态,我们只能判断日历事件表最大id的是否变化
  • 接下来提供详细java代码
package com.triedtech.triedapp.plugins.calendar;

import java.util.TimeZone;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

import android.provider.CalendarContract.Events;
import android.util.Log;

public class Calendar extends CordovaPlugin {
    public static final Integer RESULT_CODE_CREATE = 0;
    private static String calanderURL = "";
    private static String calanderEventURL = "";
    private static String calanderRemiderURL = "";
    private String TAG = "calendar";
    public int isInit = 0;
    public int lastId = 0;
    private String calId;
    private CallbackContext callbackContext;

    public boolean execute(String action, JSONArray args,
            CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        initConfig();
        if (action.equals("add")) {

            JSONObject sData = args.getJSONObject(0);
            this.Add(sData, callbackContext);
            return true;
        } else if (action.equals("open")) {
            Open();
            return true;
        }
        return false;
    }

    private void initConfig() {
        if (isInit == 0) {
            if (Build.VERSION.SDK_INT >=8) {
                calanderURL = "content://com.android.calendar/calendars";
                calanderEventURL = "content://com.android.calendar/events";
                calanderRemiderURL = "content://com.android.calendar/reminders";

            } else {
                calanderURL = "content://calendar/calendars";
                calanderEventURL = "content://calendar/events";
                calanderRemiderURL = "content://calendar/reminders";
            }
            Cursor userCursor = cordova.getActivity().getContentResolver()
                    .query(Uri.parse(calanderURL), null, null, null, null);
            if (userCursor.getCount() > 0) {
                userCursor.moveToFirst();
                calId = userCursor.getString(userCursor.getColumnIndex("_id"));
            }
            isInit = 1;
        }
    }

    private void Add(final JSONObject sData, final CallbackContext context) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    ContentValues event = new ContentValues();
                    Log.v(TAG, sData.getString("dtstart"));
                    event.put("calendar_id", calId);
                    event.put(Events.TITLE, sData.getString("title"));
                    event.put(Events.EVENT_LOCATION,
                            sData.getString("location"));
                    event.put(Events.DESCRIPTION,
                            sData.getString("description"));
                    event.put(Events.DTSTART, sData.getLong("dtstart"));
                    event.put(Events.DTEND, sData.getLong("dtend"));
                    event.put("eventTimezone", TimeZone.getDefault().getID());
                    Uri url = cordova.getActivity().getContentResolver()
                            .insert(Uri.parse(calanderEventURL), event);
                    long id = Long.parseLong(url.getLastPathSegment());
                    ContentValues values = new ContentValues();
                    values.put("event_id", id);
                    // 提前10分钟有提醒
                    values.put("minutes", 10);
                    values.put("method", 1);
                    cordova.getActivity().getContentResolver()
                            .insert(Uri.parse(calanderRemiderURL), values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                context.success(); // Thread-safe.
            }
        });
    }

    private int GetLastId() {
        Cursor userCursor = cordova
                .getActivity()
                .getContentResolver()
                .query(Uri.parse(calanderEventURL), null,
                        Events.CALENDAR_ID + " =" + calId, null,
                        Events._ID + " desc limit 1");
        if (userCursor.getCount() > 0) {
            userCursor.moveToFirst();
            String event_id = userCursor.getString(userCursor
                    .getColumnIndex(Events._ID));
            userCursor.close();    
            return Integer.parseInt(event_id);
        }
        return 0;
    }

    private void Open() {
        Uri uri = Uri.parse(calanderEventURL);
        Intent intent = new Intent("android.intent.action.INSERT", uri);
        lastId = GetLastId();
        cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
        
    }
    
    private JSONObject LastRecord() throws JSONException{
        Cursor userCursor = cordova
                .getActivity()
                .getContentResolver()
                .query(Uri.parse(calanderEventURL), null,
                        Events.CALENDAR_ID + " =" + calId, null,
                        Events._ID + " desc limit 1");
        userCursor.moveToFirst();
        String event_id = userCursor.getString(userCursor
                .getColumnIndex(Events._ID));
        JSONObject record = new JSONObject();
        Log.v(TAG, userCursor.getString(userCursor.getColumnIndex(Events.TITLE)));
        record.put("dtstart", userCursor.getString(userCursor.getColumnIndex(Events.DTSTART)));
        record.put("dtend", userCursor.getString(userCursor.getColumnIndex(Events.DTEND)));
        record.put("id", userCursor.getString(userCursor.getColumnIndex(Events._ID)));
        record.put("location", userCursor.getString(userCursor.getColumnIndex(Events.EVENT_LOCATION)));
        record.put("title", userCursor.getString(userCursor.getColumnIndex(Events.TITLE)));
        record.put("description", userCursor.getString(userCursor.getColumnIndex(Events.DESCRIPTION)));
        userCursor.close();
        
        return record;
    }

    /**
     * Called when the calendar view exits.
     * 
     * @param requestCode
     *            The request code originally supplied to
     *            startActivityForResult(), allowing you to identify who this
     *            result came from.
     * @param resultCode
     *            The integer result code returned by the child activity through
     *            its setResult().
     * @param intent
     *            An Intent, which can return result data to the caller (various
     *            data can be attached to Intent "extras").
     */
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.v(TAG,String.valueOf(lastId));
        Log.v(TAG,String.valueOf(GetLastId()));
        if (lastId != GetLastId()) {
            try {
                Log.v(TAG,"执行");
                this.callbackContext.success(LastRecord());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    
}

 

 

posted @ 2013-11-24 09:44  Peter_zhou  阅读(1371)  评论(0编辑  收藏  举报