Java Code Examples for android.provider.CalendarContract

The following examples show how to use android.provider.CalendarContract. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 检查是否存在日历账户
 *
 * @return 存在:日历账户ID  不存在:-1
 */
private static long checkCalendarAccount(Context context) {
    try (Cursor cursor = context.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI,
            null, null, null, null)) {
        // 不存在日历账户
        if (null == cursor) {
            return -1;
        }
        int count = cursor.getCount();
        // 存在日历账户,获取第一个账户的ID
        if (count > 0) {
            cursor.moveToFirst();
            return cursor.getInt(cursor.getColumnIndex(CalendarContract.Calendars._ID));
        } else {
            return -1;
        }
    }
}
 
Example 2
Source Project: haxsync   Source File: WizardActivity.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void readSettings(){
  	Account account = DeviceUtil.getAccount(this);
  	boolean contactSync = true;
  	boolean calendarSync = true;
  	if (account != null){
   	contactSync = ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY);
   	calendarSync = ContentResolver.getSyncAutomatically(account, CalendarContract.AUTHORITY);
  	}
SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_MULTI_PROCESS);

  	if (!contactSync)
  		contactSpinner.setSelection(0);
  	else if (prefs.getBoolean("phone_only", true))
  		contactSpinner.setSelection(1);
  	else
  		contactSpinner.setSelection(2);
  	
eventSwitch.setChecked(prefs.getBoolean("sync_events", true) && calendarSync);
birthdaySwitch.setChecked(prefs.getBoolean("sync_birthdays", true) && calendarSync);
reminderSwitch.setChecked(prefs.getBoolean("event_reminders", true));
wizardCheck.setChecked(!DeviceUtil.isWizardShown(this));
toggleReminderVisibility();
  }
 
Example 3
/**
 * 更新指定ID事件的结束时间
 *
 * @return If successfully returns 1
 */
public static int updateCalendarEventEndTime(Context context, long eventID, long newEndTime) {
    checkContextNull(context);

    Uri uri = CalendarContract.Events.CONTENT_URI;

    // 新的数据
    ContentValues event = new ContentValues();
    event.put(CalendarContract.Events.DTEND, newEndTime);


    // 匹配条件
    String selection = "(" + CalendarContract.Events._ID + " = ?)";
    String[] selectionArgs = new String[]{String.valueOf(eventID)};

    return context.getContentResolver().update(uri, event, selection, selectionArgs);
}
 
Example 4
/**
 * 更新指定ID事件的起始时间
 *
 * @return If successfully returns 1
 */
public static int updateCalendarEventTime(Context context, long eventID, long newBeginTime,
                                          long newEndTime) {
    checkContextNull(context);

    Uri uri = CalendarContract.Events.CONTENT_URI;

    // 新的数据
    ContentValues event = new ContentValues();
    event.put(CalendarContract.Events.DTSTART, newBeginTime);
    event.put(CalendarContract.Events.DTEND, newEndTime);


    // 匹配条件
    String selection = "(" + CalendarContract.Events._ID + " = ?)";
    String[] selectionArgs = new String[]{String.valueOf(eventID)};

    return context.getContentResolver().update(uri, event, selection, selectionArgs);
}
 
Example 5
/**
 * 更新指定ID事件的描述
 *
 * @return If successfully returns 1
 */
public static int updateCalendarEventDes(Context context, long eventID, String newEventDes) {
    checkContextNull(context);

    Uri uri = CalendarContract.Events.CONTENT_URI;

    // 新的数据
    ContentValues event = new ContentValues();
    event.put(CalendarContract.Events.DESCRIPTION, newEventDes);


    // 匹配条件
    String selection = "(" + CalendarContract.Events._ID + " = ?)";
    String[] selectionArgs = new String[]{String.valueOf(eventID)};

    return context.getContentResolver().update(uri, event, selection, selectionArgs);
}
 
Example 6
Source Project: mOrgAnd   Source File: CalendarWrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public int getCalendarID(String calendarName) {
	Cursor cursor = context.getContentResolver().query(
			CalendarContract.Calendars.CONTENT_URI,
			new String[] { CalendarContract.Calendars._ID,
                       CalendarContract.Calendars.CALENDAR_DISPLAY_NAME }, null, null,
			null);
	if (cursor != null && cursor.moveToFirst()) {
		for (int i = 0; i < cursor.getCount(); i++) {
			int calId = cursor.getInt(0);
			String calName = cursor.getString(1);

			if (calName.equals(calendarName)) {
				cursor.close();
				return calId;
			}
			cursor.moveToNext();
		}
		cursor.close();
	}
	return -1;
}
 
Example 7
/**
 * 更新指定ID事件的常用信息(标题、描述、地点)
 *
 * @return If successfully returns 1
 */
public static int updateCalendarEventCommonInfo(Context context, long eventID, String newEventTitle,
                                                String newEventDes, String newEventLocation) {
    checkContextNull(context);

    Uri uri = CalendarContract.Events.CONTENT_URI;

    // 新的数据
    ContentValues event = new ContentValues();
    event.put(CalendarContract.Events.TITLE, newEventTitle);
    event.put(CalendarContract.Events.DESCRIPTION, newEventDes);
    event.put(CalendarContract.Events.EVENT_LOCATION, newEventLocation);


    // 匹配条件
    String selection = "(" + CalendarContract.Events._ID + " = ?)";
    String[] selectionArgs = new String[]{String.valueOf(eventID)};

    return context.getContentResolver().update(uri, event, selection, selectionArgs);
}
 
Example 8
public static void setCalendarColor(Context context, Account account, String name, int color){
	mContentResolver = context.getContentResolver();
	long calID = getCalendarID(account, name);
	if (calID == -2){
		return;
	}
	ContentValues values = new ContentValues();
	values.put(CalendarContract.Calendars.CALENDAR_COLOR, color);
	Uri calcUri = CalendarContract.Calendars.CONTENT_URI.buildUpon()
			.appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")
			.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account.name)
			.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, account.type)
			.build();

	mContentResolver.update(calcUri, values, CalendarContract.Calendars._ID + " = " + calID, null);

	
}
 
Example 9
/**
 * 通过Intent启动系统日历新建事件界面插入新的事件
 * <p>
 * TIP: 这将不再需要声明读写日历数据的权限
 *
 * @param beginTime 事件开始时间
 * @param endTime   事件结束时间
 * @param title     事件标题
 * @param des       事件描述
 * @param location  事件地点
 * @param isAllDay  事件是否全天
 */
public static void startCalendarForIntentToInsert(Context context, long beginTime, long endTime,
                                                  String title, String des, String location,
                                                  boolean isAllDay) {
    checkCalendarAccount(context);


    // FIXME: 2019/3/6 VIVO手机无法打开界面,找不到对应的Activity  com.bbk.calendar
    Intent intent = new Intent(Intent.ACTION_INSERT)
            .setData(CalendarContract.Events.CONTENT_URI)
            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime)
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime)
            .putExtra(CalendarContract.Events.ALL_DAY, isAllDay)
            .putExtra(CalendarContract.Events.TITLE, title)
            .putExtra(CalendarContract.Events.DESCRIPTION, des)
            .putExtra(CalendarContract.Events.EVENT_LOCATION, location);

    if (null != intent.resolveActivity(context.getPackageManager())) {
        context.startActivity(intent);
    }
}
 
Example 10
Source Project: biermacht   Source File: BrewTimerStepFragment.java    License: Apache License 2.0 6 votes vote down vote up
private long getCalendarId() {
  String[] projection = new String[]{Calendars._ID};
  //String selection = Calendars.ACCOUNT_NAME + "=Biermacht AND" + Calendars.ACCOUNT_TYPE + "=" + CalendarContract.ACCOUNT_TYPE_LOCAL;

  String selection = "(" + Calendars.ACCOUNT_NAME + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?)";
  String[] selectionArgs = new String[]{"Biermacht", CalendarContract.ACCOUNT_TYPE_LOCAL};

  // use the same values as above:
  //String[] selArgs = new String[]{"Biermacht", CalendarContract.ACCOUNT_TYPE_LOCAL};
  Cursor cursor = c.getContentResolver().query(Calendars.CONTENT_URI,
                                               projection,
                                               selection,
                                               selectionArgs,
                                               null);
  if (cursor.moveToFirst()) {
    return cursor.getLong(0);
  }
  return - 1;
}
 
Example 11
Source Project: Wrox-ProfessionalAndroid-4E   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void listing10_26() {
  // Listing 10-26: Inserting a new calendar event using an Intent

  // Create a new insertion Intent.
  Intent intent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);

  // Add the calendar event details
  intent.putExtra(CalendarContract.Events.TITLE, "Book Launch!");
  intent.putExtra(CalendarContract.Events.DESCRIPTION, "Professional Android Release!");
  intent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Wrox.com");

  Calendar startTime = Calendar.getInstance();
  startTime.set(2018, 6, 19, 0, 30);
  intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime.getTimeInMillis());

  // Use the Calendar app to add the new event.
  startActivity(intent);
}
 
Example 12
Source Project: ETSMobile-Android2   Source File: AndroidCalendarManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a string containing all user's calendars
 * @return
 */
public String selectAllCalendars() {
    Cursor calendarCursor = context.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, projection, null, null, null);
    String response = "";

    if (calendarCursor.moveToFirst()) {
        do {
            long id = calendarCursor.getLong(0);
            String accountName = calendarCursor.getString(1);
            String calendarDisplayName = calendarCursor.getString(2);
            String name = calendarCursor.getString(3);
            String calendarColor = calendarCursor.getString(4);

            response += id+"-"+accountName+"-"+calendarDisplayName+"-"+name+"-"+calendarColor+"\n";

        } while (calendarCursor.moveToNext());
    }
    calendarCursor.close();
    return response;
}
 
Example 13
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    parentAct = getActivity();
    ArrayList<String> calendars = getArguments().getStringArrayList("calendars");
    return new AlertDialog.Builder(getActivity())
            .setAdapter(new CalendarAdapter(getActivity(), calendars), (dialog, which) -> {
                CalendarInsertHandler cih = new CalendarInsertHandler(getActivity()
                        .getContentResolver());
                ArrayList<ContentValues> cvList = getArguments().getParcelableArrayList(
                        "valuesList");
                ArrayList<Integer> indices = getArguments().getIntegerArrayList("indices");
                int selection = indices.get(which);

                for (int i = 0; i < cvList.size(); i++) {
                    cvList.get(i).put(CalendarContract.Events.CALENDAR_ID, selection);
                    cih.startInsert(i, null, CalendarContract.Events.CONTENT_URI, cvList.get(i));
                }
            })
            .setTitle("Select calendar")
            .create();
}
 
Example 14
Source Project: ToDay   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void createLocalCalendar() {
    String name = getString(R.string.default_calendar_name);
    ContentValues cv = new ContentValues();
    cv.put(CalendarContract.Calendars.ACCOUNT_NAME, BuildConfig.APPLICATION_ID);
    cv.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
    cv.put(CalendarContract.Calendars.NAME, name);
    cv.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, name);
    cv.put(CalendarContract.Calendars.CALENDAR_COLOR, 0);
    cv.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
            CalendarContract.Calendars.CAL_ACCESS_OWNER);
    cv.put(CalendarContract.Calendars.OWNER_ACCOUNT, BuildConfig.APPLICATION_ID);
    new CalendarQueryHandler(getContentResolver())
            .startInsert(0, null, CalendarContract.Calendars.CONTENT_URI
                            .buildUpon()
                            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "1")
                            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME,
                                    BuildConfig.APPLICATION_ID)
                            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE,
                                    CalendarContract.ACCOUNT_TYPE_LOCAL)
                            .build()
                    , cv);
}
 
Example 15
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void addEventOnCalendar(PersianDate persianDate) {
    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setData(CalendarContract.Events.CONTENT_URI);

    CivilDate civil = DateConverter.persianToCivil(persianDate);

    intent.putExtra(CalendarContract.Events.DESCRIPTION,
            mPersianCalendarHandler.dayTitleSummary(persianDate));

    Calendar time = Calendar.getInstance();
    time.set(civil.getYear(), civil.getMonth() - 1, civil.getDayOfMonth());

    intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
            time.getTimeInMillis());
    intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
            time.getTimeInMillis());
    intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);

    startActivity(intent);
}
 
Example 16
Source Project: ETSMobile-Android2   Source File: HoraireFragment.java    License: Apache License 2.0 6 votes vote down vote up
protected void onPostExecute(Object result) {

            customProgressDialog.dismiss();
            if (exception != null) {
                Toast.makeText(getActivity(), getString(R.string.toast_Calendar_Update_Error), Toast.LENGTH_SHORT).show();
            } else {

                //Launch native calendar app
                long startMillis = java.lang.System.currentTimeMillis();
                Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
                builder.appendPath("time");
                ContentUris.appendId(builder, startMillis);

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(builder.build());

                startActivity(intent);

            }
        }
 
Example 17
Source Project: intra42   Source File: Calendar.java    License: Apache License 2.0 6 votes vote down vote up
private static void removeEventFromCalendar(Context context, int event) {

        Uri eventsUri = Uri.parse("content://com.android.calendar/events");

        ContentResolver resolver = context.getContentResolver();

        String selection = CalendarContract.Events.CUSTOM_APP_URI + " = ?";
        String[] selectionArgs = {getEventUri(event)};

        Cursor cursor = resolver.query(eventsUri, new String[]{"_id"}, selection, selectionArgs, null);
        while (cursor.moveToNext()) {
            long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
            resolver.delete(ContentUris.withAppendedId(eventsUri, eventId), null, null);
        }
        cursor.close();
    }
 
Example 18
Source Project: ETSMobile-Android2   Source File: AndroidCalendarManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the id of the specified calendar
 * @param calendarName
 * @return id
 */
public int getCalendarId(String calendarName) throws Exception {

    String selection = "(" + CalendarContract.Calendars.CALENDAR_DISPLAY_NAME+ " = ?)";
    String[] selectionArgs = new String[] {calendarName};
    Cursor calendarCursor = context.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, new String[] {CalendarContract.Calendars._ID,
            CalendarContract.Calendars.ACCOUNT_NAME,
            CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
            CalendarContract.Calendars.NAME,
            CalendarContract.Calendars.CALENDAR_COLOR}, selection, selectionArgs, null);

    long id = 0;
    if (calendarCursor.moveToFirst()) {
        id = calendarCursor.getLong(0);
    }

    if(id==0) {
        throw new Exception("Calendar not found");
    }

    calendarCursor.close();
    return (int)id;

}
 
Example 19
Source Project: RememBirthday   Source File: EventProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Utility method for add values in Builder
 * @param builder ContentProviderOperation.Builder
 * @param event Event to add
 */
private static synchronized void assignValuesInBuilder(ContentProviderOperation.Builder builder, CalendarEvent event) {
    if(event.isAllDay()) {
        // ALL_DAY events must be UTC
        DateTime dateTimeStartUTC = new DateTime(event.getDateStart()).withZoneRetainFields(DateTimeZone.UTC);
        DateTime dateTimeStopUTC = new DateTime(event.getDateStop()).withZoneRetainFields(DateTimeZone.UTC);
        builder.withValue(CalendarContract.Events.DTSTART, dateTimeStartUTC.toDate().getTime());
        builder.withValue(CalendarContract.Events.DTEND, dateTimeStopUTC.toDate().getTime());
        builder.withValue(CalendarContract.Events.EVENT_TIMEZONE, "UTC");
        builder.withValue(CalendarContract.Events.ALL_DAY, 1);
    } else {
        builder.withValue(CalendarContract.Events.DTSTART, event.getDateStart().getTime());
        builder.withValue(CalendarContract.Events.DTEND, event.getDateStop().getTime());
        builder.withValue(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    }
    builder.withValue(CalendarContract.Events.TITLE, event.getTitle());
}
 
Example 20
Source Project: ETSMobile-Android2   Source File: AndroidCalendarManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Insert an event in the local calendar
 * @param calendarName
 * @param title
 * @param description
 * @param place
 * @param start
 * @param end
 * @throws Exception
 */
public void insertEventInCalendar(String calendarName,String title,String description, String place, Date start, Date end) throws Exception {
    int calendarId = getCalendarId(calendarName);

    Calendar beginTime = Calendar.getInstance();
    beginTime.setTime(start);

    Calendar endTime = Calendar.getInstance();
    endTime.setTime(end);

    ContentValues values = new ContentValues();
    values.put(CalendarContract.Events.DTSTART, beginTime.getTimeInMillis());
    values.put(CalendarContract.Events.DTEND, endTime.getTimeInMillis());
    values.put(CalendarContract.Events.TITLE, title);
    values.put(CalendarContract.Events.DESCRIPTION, description);
    values.put(CalendarContract.Events.EVENT_LOCATION, place);
    values.put(CalendarContract.Events.CALENDAR_ID,calendarId );
    values.put(CalendarContract.Events.EVENT_TIMEZONE, "America/Montreal");

    context.getContentResolver().insert(CalendarContract.Events.CONTENT_URI, values);
}
 
Example 21
Source Project: RememBirthday   Source File: EventLoader.java    License: GNU General Public License v3.0 6 votes vote down vote up
public synchronized static void deleteEventsFromContact(Context context, Contact contact) {
    ArrayList<ContentProviderOperation> operations = new ArrayList<>();
    try {
        for (CalendarEvent event : getEventsSavedForEachYear(context, contact)) {
            operations.add(ReminderProvider.deleteAll(context, event.getId()));
            operations.add(EventProvider.delete(event));
        }
        ContentProviderResult[] contentProviderResults =
                context.getContentResolver().applyBatch(CalendarContract.AUTHORITY, operations);
        for(ContentProviderResult contentProviderResult : contentProviderResults) {
            Log.d(TAG, contentProviderResult.toString());
            if (contentProviderResult.uri != null)
                Log.d(TAG, contentProviderResult.uri.toString());
        }
    } catch (RemoteException |OperationApplicationException |EventException e) {
        Log.e(TAG, "Unable to deleteById events : " + e.getMessage());
    }
}
 
Example 22
Source Project: mCalendar   Source File: CalendarProvider.java    License: Apache License 2.0 5 votes vote down vote up
public void insertReminderForTask(long eventId, int minutes, int method) {
    ContentValues values = new ContentValues();
    values.put(CalendarContract.Reminders.EVENT_ID, eventId);
    values.put(CalendarContract.Reminders.MINUTES, minutes);
    values.put(CalendarContract.Reminders.METHOD, method);
    contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, values);
}
 
Example 23
Source Project: mOrgAnd   Source File: CalendarWrapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void addReminder(String eventID, long beginTime, long endTime) {
	if (beginTime < System.currentTimeMillis())
		return;

	ContentValues reminderValues = new ContentValues();
	reminderValues.put(CalendarContract.Reminders.MINUTES, this.reminderTime);
	reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventID);
	reminderValues.put(CalendarContract.Reminders.METHOD,
               CalendarContract.Reminders.METHOD_ALERT);
	context.getContentResolver().insert(CalendarContract.Reminders.CONTENT_URI,
			reminderValues);

	ContentValues alertvalues = new ContentValues();
	alertvalues.put(CalendarContract.CalendarAlerts.EVENT_ID, eventID);
	alertvalues.put(CalendarContract.CalendarAlerts.BEGIN, beginTime);
	alertvalues.put(CalendarContract.CalendarAlerts.END, endTime);
	alertvalues.put(CalendarContract.CalendarAlerts.STATE,
			CalendarContract.CalendarAlerts.STATE_SCHEDULED);
	alertvalues.put(CalendarContract.CalendarAlerts.MINUTES, this.reminderTime);
	context.getContentResolver().insert(
			CalendarContract.CalendarAlerts.CONTENT_URI, alertvalues);

	ContentValues eventValues = new ContentValues();
	eventValues.put(CalendarContract.Events.HAS_ALARM, 1);
	context.getContentResolver().update(
			ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI,
					Long.valueOf(eventID)), eventValues, null, null);
}
 
Example 24
public static ContentProviderOperation updateWithUnknownId(Context context, long eventId, Reminder reminder, int newMinutes) {
    // TODO update
    ContentProviderOperation.Builder builder = ContentProviderOperation
            .newUpdate(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
            .withSelection(CalendarContract.Reminders.EVENT_ID + " =?"
                            + " AND " + CalendarContract.Reminders.MINUTES + " =?"
                    , new String[]{String.valueOf(eventId),
                            String.valueOf(reminder.getMinutesBeforeEvent())})
            .withValue(CalendarContract.Reminders.MINUTES, newMinutes);
    return  builder.build();
}
 
Example 25
/**
 * 更新指定ID事件的提醒方式
 *
 * @return If successfully returns 1
 */
private static int updateCalendarEventReminder(Context context, long eventID, long newAdvanceTime) {
    checkContextNull(context);

    Uri uri = CalendarContract.Reminders.CONTENT_URI;

    ContentValues reminders = new ContentValues();
    reminders.put(CalendarContract.Reminders.MINUTES, newAdvanceTime);

    // 更新匹配条件
    String selection2 = "(" + CalendarContract.Reminders.EVENT_ID + " = ?)";
    String[] selectionArgs2 = new String[]{String.valueOf(eventID)};

    return context.getContentResolver().update(uri, reminders, selection2, selectionArgs2);
}
 
Example 26
/**
 * 判断日历账户中是否已经存在此事件
 *
 * @param begin 事件开始时间
 * @param end   事件结束时间
 * @param title 事件标题
 */
public static boolean isEventAlreadyExist(Context context, long begin, long end, String title) {
    String[] projection = new String[]{
            CalendarContract.Instances.BEGIN,
            CalendarContract.Instances.END,
            CalendarContract.Instances.TITLE
    };

    Cursor cursor = CalendarContract.Instances.query(
            context.getContentResolver(), projection, begin, end, title);

    return null != cursor && cursor.moveToFirst()
            && cursor.getString(
            cursor.getColumnIndex(CalendarContract.Instances.TITLE)).equals(title);
}
 
Example 27
/**
 * 组装日历事件
 */
private static void setupEvent(CalendarEvent calendarEvent, ContentValues event) {
    // 事件开始时间
    event.put(CalendarContract.Events.DTSTART, calendarEvent.getStart());
    // 事件结束时间
    event.put(CalendarContract.Events.DTEND, calendarEvent.getEnd());
    // 事件标题
    event.put(CalendarContract.Events.TITLE, calendarEvent.getTitle());
    // 事件描述(对应手机系统日历备注栏)
    event.put(CalendarContract.Events.DESCRIPTION, calendarEvent.getDescription());
    // 事件地点
    event.put(CalendarContract.Events.EVENT_LOCATION, calendarEvent.getEventLocation());
    // 事件时区
    event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    // 定义事件的显示,默认即可
    event.put(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_DEFAULT);
    // 事件的状态
    event.put(CalendarContract.Events.STATUS, 0);
    // 设置事件提醒警报可用
    event.put(CalendarContract.Events.HAS_ALARM, 1);
    // 设置事件忙
    event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
    if (null != calendarEvent.getRRule()) {
        // 设置事件重复规则
        event.put(CalendarContract.Events.RRULE,
                getFullRRuleForRRule(calendarEvent.getRRule(),
                        calendarEvent.getStart(), calendarEvent.getEnd()));
    }
}
 
Example 28
Source Project: android_9.0.0_r45   Source File: TextClassifierImpl.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
private static LabeledIntent createCalendarViewIntent(Context context, Instant parsedTime) {
    Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
    builder.appendPath("time");
    ContentUris.appendId(builder, parsedTime.toEpochMilli());
    return new LabeledIntent(
            context.getString(com.android.internal.R.string.view_calendar),
            context.getString(com.android.internal.R.string.view_calendar_desc),
            new Intent(Intent.ACTION_VIEW).setData(builder.build()),
            LabeledIntent.DEFAULT_REQUEST_CODE);
}
 
Example 29
Source Project: mCalendar   Source File: TaskActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);

    year = getIntent().getIntExtra("year",0);
    month = getIntent().getIntExtra("month", 0);
    day = getIntent().getIntExtra("day", 0);

    edit = getIntent().getBooleanExtra("edit", false);
    taskId = getIntent().getLongExtra("taskId", -1);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TaskBean taskBean = genTask();
            if (!edit){
                if (taskBean != null){
                    // TODO: 15/11/3 Insert by calendar id.
                    taskId = CalendarProvider.getStaticInstance(TaskActivity.this).insertTask(taskBean, 1);
                }
            } else {
                CalendarProvider.getStaticInstance(TaskActivity.this).updateTask(taskId, taskBean);
            }
            int reminderSpinnerPos = reminder.getSelectedItemPosition();
            if ( reminderSpinnerPos != 0){
                CalendarProvider.getStaticInstance(TaskActivity.this).insertReminderForTask(taskId, Constants.REMINDER_VALUE[reminderSpinnerPos], CalendarContract.Reminders.METHOD_DEFAULT);
            }
            TaskActivity.this.finish();
        }
    });

    initUI();
}
 
Example 30
Source Project: PermissionAgent   Source File: CalendarWriteTester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean test() throws Throwable {
    try {
        TimeZone timeZone = TimeZone.getDefault();
        ContentValues value = new ContentValues();
        value.put(CalendarContract.Calendars.NAME, NAME);
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT);
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, NAME);
        value.put(CalendarContract.Calendars.VISIBLE, 1);
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
        value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, NAME);
        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri insertUri = CalendarContract.Calendars.CONTENT_URI.buildUpon()
            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, NAME)
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
            .build();
        Uri resourceUri = mResolver.insert(insertUri, value);
        return ContentUris.parseId(resourceUri) > 0;
    } finally {
        Uri deleteUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().build();
        mResolver.delete(deleteUri, CalendarContract.Calendars.ACCOUNT_NAME + "=?", new String[] {ACCOUNT});
    }
}
 
Example 31
Source Project: PermissionAgent   Source File: CalendarReadTester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean test() throws Throwable {
    String[] projection = new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.NAME};
    Cursor cursor = mResolver.query(CalendarContract.Calendars.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
        try {
            CursorTest.read(cursor);
        } finally {
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example 32
Source Project: PermissionAgent   Source File: CalendarWriteTester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean test() throws Throwable {
    try {
        TimeZone timeZone = TimeZone.getDefault();
        ContentValues value = new ContentValues();
        value.put(CalendarContract.Calendars.NAME, NAME);
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT);
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, NAME);
        value.put(CalendarContract.Calendars.VISIBLE, 1);
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
        value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, NAME);
        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri insertUri = CalendarContract.Calendars.CONTENT_URI.buildUpon()
            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, NAME)
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
            .build();
        Uri resourceUri = mResolver.insert(insertUri, value);
        return ContentUris.parseId(resourceUri) > 0;
    } finally {
        Uri deleteUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().build();
        mResolver.delete(deleteUri, CalendarContract.Calendars.ACCOUNT_NAME + "=?", new String[] {ACCOUNT});
    }
}
 
Example 33
Source Project: PermissionAgent   Source File: CalendarReadTester.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean test() throws Throwable {
    String[] projection = new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.NAME};
    Cursor cursor = mResolver.query(CalendarContract.Calendars.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
        try {
            CursorTest.read(cursor);
        } finally {
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example 34
public static ContentProviderOperation deleteWithUnknownId(Context context, long eventId, Reminder reminder) {
    // TODO delete
    ContentProviderOperation.Builder builder = ContentProviderOperation
            .newDelete(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
            .withSelection(CalendarContract.Reminders.EVENT_ID + " =?"
                            + " AND " + CalendarContract.Reminders.MINUTES + " =?"
                    , new String[]{String.valueOf(eventId),
                            String.valueOf(reminder.getMinutesBeforeEvent())});
    return  builder.build();
}
 
Example 35
Source Project: imsdk-android   Source File: CalendarReminderUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 添加日历账户,账户创建成功则返回账户id,否则返回-1
 */
private static long addCalendarAccount(Context context) {
    TimeZone timeZone = TimeZone.getDefault();
    ContentValues value = new ContentValues();
    value.put(CalendarContract.Calendars.NAME, CALENDARS_NAME);
    String accountName = CurrentPreference.getInstance().getUserid()+"@" + QtalkNavicationService.getInstance().getEmail();
    value.put(CalendarContract.Calendars.ACCOUNT_NAME, accountName);
    value.put(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE);
    value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CALENDARS_DISPLAY_NAME);
    value.put(CalendarContract.Calendars.VISIBLE, 1);
    value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
    value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
    value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
    value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
    value.put(CalendarContract.Calendars.OWNER_ACCOUNT, accountName);
    value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

    Uri calendarUri = Uri.parse(CALENDER_URL);
    calendarUri = calendarUri.buildUpon()
            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
            .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE)
            .build();

    Uri result = context.getContentResolver().insert(calendarUri, value);
    long id = result == null ? -1 : ContentUris.parseId(result);
    return id;
}
 
Example 36
public static ContentProviderOperation deleteAll(Context context, long eventId) {
    ContentProviderOperation.Builder builder = ContentProviderOperation
            .newDelete(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
            .withSelection(CalendarContract.Reminders.EVENT_ID + " =?"
                    , new String[]{String.valueOf(eventId)});
    return  builder.build();
}
 
Example 37
public static ContentProviderOperation update(Context context, long eventId, Reminder reminder) {
    ContentProviderOperation.Builder builder = ContentProviderOperation
            .newUpdate(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
        .withSelection(CalendarContract.Reminders._ID + " =?"
                + " AND " + CalendarContract.Reminders.EVENT_ID + " =?"
            , new String[]{String.valueOf(reminder.getId()),
                String.valueOf(eventId)})
        .withValue(CalendarContract.Reminders.MINUTES, reminder.getMinutesBeforeEvent());
    return  builder.build();
}
 
Example 38
Source Project: Wrox-ProfessionalAndroid-4E   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void listing10_27() {
  // Listing 10-27: Viewing a calendar event using an Intent

  // Create a URI addressing a specific event by its row ID.
  // Use it to create a new edit Intent.
  long rowID = 760;
  Uri uri = ContentUris.withAppendedId(
    CalendarContract.Events.CONTENT_URI, rowID);

  Intent intent = new Intent(Intent.ACTION_VIEW, uri);

  // Use the Calendar app to view the calendar entry.
  startActivity(intent);
}
 
Example 39
Source Project: RememBirthday   Source File: EventProvider.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a new ContentProviderOperation to insert an event
 */
public static ContentProviderOperation insert(Context context, long calendarId,
                                              CalendarEvent event, @Nullable Contact contact) {
    ContentProviderOperation.Builder builder;

    builder = ContentProviderOperation.newInsert(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Events.CONTENT_URI));
    builder.withValue(CalendarContract.Events.CALENDAR_ID, calendarId);
    assignValuesInBuilder(builder, event);

    builder.withValue(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED);

    /*
     * Enable reminders for this event
     * Note: Needs to be explicitly set on Android < 4 to enable reminders
     */
    builder.withValue(CalendarContract.Events.HAS_ALARM, 1);

    /*
     * Set availability to free.
     * Note: HTC calendar (4.0.3 Android + HTC Sense 4.0) will show a conflict with other events
     * if availability is not set to free!
     */
    if (Build.VERSION.SDK_INT >= 14) {
        builder.withValue(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE);
    }

    // add button to open contact
    if (Build.VERSION.SDK_INT >= 16 && contact != null && contact.getLookUpKey() != null) {
        builder.withValue(CalendarContract.Events.CUSTOM_APP_PACKAGE, context.getPackageName());
        Uri contactLookupUri = Uri.withAppendedPath(
                ContactsContract.Contacts.CONTENT_LOOKUP_URI, contact.getLookUpKey());
        builder.withValue(CalendarContract.Events.CUSTOM_APP_URI, contactLookupUri.toString());
    }
    Log.d(TAG, "Build insert event : " + event);
    return builder.build();
}
 
Example 40
Source Project: ToDay   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String selection = null;
    String[] selectionArgs = null;
    if (id == LOADER_LOCAL_CALENDAR) {
        selection = CalendarContract.Calendars.ACCOUNT_TYPE + "=?";
        selectionArgs = new String[]{String.valueOf(CalendarContract.ACCOUNT_TYPE_LOCAL)};
    }
    return new CursorLoader(this,
            CalendarContract.Calendars.CONTENT_URI,
            CalendarCursor.PROJECTION, selection, selectionArgs,
            CalendarContract.Calendars.DEFAULT_SORT_ORDER);
}