3

我正在尝试以编程方式将事件添加到用户的日历中。我在 StackOverflow 和其他地方遵循了无数指南,但没有一个能让那个该死的事件出现在我的日历中。这是我当前的代码:

public void saveGamesToCalendar() {
    showCalendarPopup();
}

private void showCalendarPopup() {
    final ContentResolver cr;
    final Cursor result;
    final Uri uri;
    List<String> listCals = new ArrayList<String>();
    final String[] projection = new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CalendarContract.Calendars.NAME,};

    uri = CalendarContract.Calendars.CONTENT_URI;

    cr = context.getContentResolver();
    result = cr.query(uri, projection, null, null, null);
    if(result.getCount() > 0 && result.moveToFirst()) {
        do {
                listCals.add(result.getString(result.getColumnIndex(CalendarContract.Calendars.NAME)));
    } while(result.moveToNext());
}
CharSequence[] calendars = listCals.toArray(new CharSequence[listCals.size()]);

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Calendar to use:");
builder.setItems(calendars, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog,int itemCal) {
            Log.e("SettingsActivity", "CalendarID: " + itemCal);
            loopThroughGames(itemCal);
        };
    });
    AlertDialog alert = builder.create();
    alert.show();
}

private void loopThroughGames(int whichCalendar) {
    ArrayList<Model_Game> games = memoryManager.getGames();

    // for(Game e: games)
    Log.e("Game", games.get(101).toString());
    addGameToCalendar(games.get(101), whichCalendar);

    Log.e("ID", "" + whichCalendar);
}

private void addGameToCalendar(Model_Game game,int whichCalendar) {
    ContentResolver cr = context.getContentResolver();
    ContentValues values = new ContentValues();

    try {
        values.put(CalendarContract.Events.CALENDAR_ID, whichCalendar);
        values.put(CalendarContract.Events.TITLE, "Hockey- " + game.getLeague() + ": " + game.getTeamH() + " vs " + game.getTeamA());
        values.put(CalendarContract.Events.EVENT_LOCATION, "Twin Rinks Ice Arena- " + game.getRink() + " Rink");
        values.put(CalendarContract.Events.DTSTART, "" + game.getCalendarObject().getTimeInMillis());
        //values.put(CalendarContract.Events.DTEND, "" + game.getCalendarObject().getTimeInMillis() + 5400000);
        values.put(CalendarContract.Events.DURATION, "" + 5400000);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());

        cr.insert(CalendarContract.Events.CONTENT_URI, values);
    } catch(Exception e) {
        Log.e("Error", e.getMessage());
        toast(e.getMessage());
    }
}

基本上正在发生的事情是用户按下操作栏按钮,该按钮调用该saveGamesToCalendar()方法,该方法调用该ShowCalendarPopup()方法。此方法显示一个带有用户日历列表的标准对话框,当用户选择其中一个时,将loopThroughGames()调用该方法,并将所选日历的 ID 作为参数。当一切正常时,此方法会将用户的所有游戏写入日历,但出于测试目的,它只写入一个。该addGameToCalendar()方法采用一个游戏对象,该对象包含许多值,如时间、标题、位置、日期等,并使用网络上许多不同地方概述的标准方式将其插入日历。

我没有收到此代码的错误消息(除了我自己发送到错误日志的错误消息),所以我不知道为什么此代码不起作用。没有错误,只是游戏从未出现在我的日历中。我在清单中正确设置了权限,所以我知道这不是问题。

有没有人可以解决这个烦人的问题?谢谢你的帮助!

4

3 回答 3

7

[重新编辑]] 这就是我所做的,它就像一个魅力..

         Cursor cursor = null ;

         String[] projection = new String[] {
                   CalendarContract.Calendars._ID,
                   CalendarContract.Calendars.ACCOUNT_NAME,};

         ContentResolver cr = context2.getContentResolver();
         cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection, null, null, null);

         if ( cursor.moveToFirst() ) {
                final String[] calNames = new String[cursor.getCount()];
                calIds = new int[cursor.getCount()];
                for (int i = 0; i < calNames.length; i++) {
                    calIds[i] = cursor.getInt(0);
                    calNames[i] = cursor.getString(1);
                    cursor.moveToNext();
                }
            }

        try {           

            ContentValues values = new ContentValues();

//          int apiLevel = android.os.Build.VERSION.SDK_INT;
//            if(apiLevel<14){
//              values.put("visibility", 0);
//
//            }
            values.put(Events.DTSTART, stTime);
            values.put(Events.DTEND, enTime);
            values.put(Events.TITLE, category);
            values.put(Events.DESCRIPTION, description);
            values.put(Events.CALENDAR_ID, calIds[0]);
            values.put(Events.EVENT_LOCATION,place);
            values.put(Events.EVENT_TIMEZONE,tZone);

            mInsert =  cr.insert(CalendarContract.Events.CONTENT_URI, values);

            Toast.makeText(context2, "Event added Successfully",
                    Toast.LENGTH_LONG).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context2, "Exception: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
于 2013-03-27T08:07:29.567 回答
0

受保护的无效事件添加(){

    try
    {
        Calendar beginTime = Calendar.getInstance();
        beginTime.set(2013, 11, 20, 8,0 );
        startMillis = beginTime.getTimeInMillis();
        Calendar endTime = Calendar.getInstance();
        endTime.set(2013, 11, 20, 8, 50);
        endMillis = endTime.getTimeInMillis();




      ContentResolver cr = this.getContentResolver();
      ContentValues values = new ContentValues();

      values.put(Events.DTSTART, startMillis);
      values.put(Events.DTEND, endMillis);
      values.put(Events.TITLE, "Hello");

      values.put(Events.CALENDAR_ID, 1);            
      values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());


if (android.os.Build.VERSION.SDK_INT <= 7) {

         uri = Uri.parse("content://calendar/events");
     } else 
     {

         uri = Uri.parse("content://com.android.calendar/events");
     }
      Uri urievent = cr.insert(uri, values);    


     } 
catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

       }

    //event = Utility.readCalendarEvent(CalnderEvent.this);
}
于 2013-12-18T13:20:14.760 回答
-2

这很有效,而且更容易理解:

     long startTime = calSet.getTimeInMillis();
           Intent intent = new Intent(Intent.ACTION_INSERT).setData(Events.CONTENT_URI)
                 .setData(Events.CONTENT_URI)
                .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime)
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startTime + (length*3600000))
                .putExtra(Events.TITLE, examName)
                .putExtra(Events.EVENT_LOCATION, venue)
                .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
                .putExtra(Events.HAS_ALARM, 1);

                 startActivity(intent);
于 2014-01-31T03:35:05.467 回答