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存在版本兼容咱們要添加java

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();
            }
        }
    }
    
}
相關文章
相關標籤/搜索