java - 事件未显示在 Android 设备日历上

标签 java android calendar background-service

我们正在开发 Android 应用程序,我们正在尝试在后台服务中静默添加事件。使用以下代码进行相同的操作:

package com.red_folder.phonegap.plugin.backgroundservice.sample;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ContentUris;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;

import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService;


@SuppressWarnings("deprecation")
public class MyService extends BackgroundService {

    private final static String TAG = MyService.class.getSimpleName();

    private String mHelloTo = "World";

    @SuppressLint("NewApi")
    @SuppressWarnings("static-access")
    @Override
    protected JSONObject doWork() {
        JSONObject result = new JSONObject();



            Log.d(TAG, "Start calendar insertion");

            JSONObject jsonArray;

            long calID = 3;
            long startMillis = 0; 
            long endMillis = 0;     
            Calendar beginTime = Calendar.getInstance();
            beginTime.set(2014, 9, 14, 7, 30);
            startMillis = beginTime.getTimeInMillis();
            Calendar endTime = Calendar.getInstance();
            endTime.set(2014, 9, 14, 8, 45);
            endMillis = endTime.getTimeInMillis();


            ContentResolver cr = getContentResolver();
            ContentValues values = new ContentValues();
            values.put(Events.DTSTART, startMillis);
            values.put(Events.DTEND, endMillis);
            values.put(Events.TITLE, "Jazzercise");
            values.put(Events.DESCRIPTION, "Group workout");
            values.put(Events.CALENDAR_ID, calID);
            values.put(Events.VISIBLE, 0);
            values.put(Events.EVENT_TIMEZONE, "America/Los_Angeles");
            Uri uri = cr.insert(Events.CONTENT_URI, values);

            // get the event ID that is the last element in the Uri
            long eventID = Long.parseLong(uri.getLastPathSegment());




            Log.d(TAG, "End calendar insertion");


        return result;  
    }

    @Override
    protected JSONObject getConfig() {
        JSONObject result = new JSONObject();

        try {
            result.put("HelloTo", this.mHelloTo);
        } catch (JSONException e) {
        }

        return result;
    }

    @Override
    protected void setConfig(JSONObject config) {
        try {
            if (config.has("HelloTo"))
                this.mHelloTo = config.getString("HelloTo");
        } catch (JSONException e) {
        }

    }     

    @Override
    protected JSONObject initialiseLatestResult() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onTimerEnabled() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onTimerDisabled() {
        // TODO Auto-generated method stub

    }


}

此代码返回一个 EVENTID,这意味着它正在向设备日历添加事件,但日历上没有显示任何事件。 我们可以做什么来在设备的日历上显示添加的事件?

最佳答案

这是我打开并写入日历的代码(包括末尾的“强制同步”)。也许您可以在那里找到答案,它完美地工作。

import java.util.Date;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;

public class TVCalendar {

    public static final String TAG = "TVCalendar";

    // Projection array. Creating indices for this array instead of doing
    // dynamic lookups improves performance.
    public static final String[] EVENT_PROJECTION = new String[] {
        Calendars._ID,                           // 0
        Calendars.ACCOUNT_NAME,                  // 1
        Calendars.CALENDAR_DISPLAY_NAME,         // 2
        Calendars.OWNER_ACCOUNT                  // 3
    };

    // The indices for the projection array above.
    private static final int PROJECTION_ID_INDEX = 0;
    private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
    private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
    private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;

    static public class CalendarEntry {
        String  room;
        String  name;
        Date    start;
        Date    end;
        String  description;
        public CalendarEntry (String pRoom, String pName, Date pStart, Date pEnd, String pDesc) {
            room=pRoom;
            name=pName;
            start=pStart;
            end=pEnd;
            description=pDesc;
        }
    }

    static String   lastCalName="";
    static long     lastCalId=-1;

    static public long openCalendar(String calName,String owner) {
        if ((lastCalId>0) && (lastCalName.equals(calName)))
            return lastCalId;
        // Run query
        TVLog.i(TAG, "Querying Calendar "+calName+" owned by "+owner);
        Cursor cur = null;
        ContentResolver cr = TVPrefs.mainActivity.getContentResolver();
        Uri uri = Calendars.CONTENT_URI;   
//      String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
//                              + Calendars.ACCOUNT_TYPE + " = ?) AND ("
//                              + Calendars.OWNER_ACCOUNT + " = ?))";
//      String[] selectionArgs = new String[] {owner, "com.google",
//              owner}; 
        // Submit the query and get a Cursor object back. 
        cur = cr.query(uri, EVENT_PROJECTION, null, null, null);
        // Use the cursor to step through the returned records
        while (cur.moveToNext()) {
            long calID = 0;
            String displayName = null;
            String accountName = null;
            String ownerName = null;

            // Get the field values
            calID = cur.getLong(PROJECTION_ID_INDEX);
            displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
            accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
            ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);

            TVLog.i(TAG, "Display: "+displayName+" Account: "+accountName+" Owner: "+ownerName);

            if (displayName.equals(calName)) {
                lastCalId=calID;
                lastCalName=calName;
                return calID;
            }

        }
        return -1;
    }

    static public boolean addEvent(String calName, String ownerName, String timeZone, CalendarEntry entry) {
        long    calId=openCalendar(calName,ownerName);
        TVLog.i(TAG, "Calendar ID: "+calId);
        if (calId>=0) {
            // Write to the Calendar
            ContentResolver cr = TVPrefs.mainActivity.getContentResolver();
            ContentValues values = new ContentValues();
            values.put(Events.DTSTART, entry.start.getTime());
            values.put(Events.DTEND, entry.end.getTime());
            values.put(Events.TITLE, entry.name);
            values.put(Events.DESCRIPTION, entry.description);
            values.put(Events.CALENDAR_ID, calId);
            values.put(Events.EVENT_TIMEZONE, timeZone);
            values.put(Events.EVENT_LOCATION, entry.room);
            values.put(Events.ACCESS_LEVEL, Events.ACCESS_PUBLIC);
            //Uri uri 
            cr.insert(Events.CONTENT_URI, values);

            // Force a sync
            Bundle extras = new Bundle();
            extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
            extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
            AccountManager am = AccountManager.get(TVPrefs.mainActivity);
            Account[] acc = am.getAccountsByType("com.google");
            Account account = null;
            if (acc.length>0) {
                account=acc[0];
                ContentResolver.requestSync(account, "com.android.calendar", extras);
            }

            return true;

            // get the event ID that is the last element in the Uri
            // long eventID = Long.parseLong(uri.getLastPathSegment());

        }
        return false;
    }
}

关于java - 事件未显示在 Android 设备日历上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933444/

相关文章:

java - 如何使代码递归地向后打印?

java - 在 JBoss Fuse 中处理非 OSGI 依赖项的传递依赖项

java - 时间广场日历app的实现方法

java - 检查用户是否对另一个 lotusCalendar 有编辑权限

java - Java 中二维 int 数组优化的洪水填充

java - 两个线程一个同步方法scjp

android - Gradle 为每个资源文件夹构建

android - "Clear User Data"机器人

javascript - 永久唯一移动设备标识符(Evercookie?)

android - TDateEdit,如何在日历选择器对话框中将前一年设置为 1900?