6

在此处输入图像描述

我已经展示了如何为我们自己的帐户设置自己的 sync_calendar 功能以及我们如何将我们自己的事件同步到......

在清单中授予 READ 和 WRITE 日历的权限

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

在 res/xml 文件夹下创建 SyncAdapter 文件名:sync_calendar.xml

<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="com.account.auth"
    android:contentAuthority="com.android.calendar"
    android:supportsUploading="false"
    android:userVisible="true" />

android:accountType:-- 此处提供您在帐户身份验证器下创建的帐户类型,就像我在下面提到的

<account-authenticator
 android:accountType="com.account.auth"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:smallIcon="@drawable/ic_launcher"
 xmlns:android="http://schemas.android.com/apk/res/android">
</account-authenticator>

在清单文件中定义服务名称和元数据

     <service
                android:name="com.account.auth.CalendarSyncAdapterService"
                android:exported="true"
                android:process=":calendar" >
                <intent-filter>
                    <action android:name="android.content.SyncAdapter" />
                </intent-filter>
            <meta-data
                android:name="android.content.SyncAdapter"
                android:resource="@xml/sync_calendar" />
</service>

创建同步开始时将调用的服务并添加要移交同步日历的逻辑

public class CalendarSyncAdapterService extends Service {

 private static SyncAdapterImpl sSyncAdapter = null;
 static MeetingsDatabaseAdapter sync_Meetings = null;

 public CalendarSyncAdapterService() {
  super();
 }

 private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
  public SyncAdapterImpl(Context context) {
   super(context, true);
   mContext = context;
  }

 @Override
 public void onPerformSync(Account account, Bundle extras,
   String authority, ContentProviderClient provider,
   SyncResult syncResult) {

        account = null;
 account = AccountManager.getAccount( mContext, AccountManager.currentUser(mContext)
       .get("username_display").toString());
 try {
  if (account != null) {
               CalendarSyncAdapterService.performSync(mContext, account,
       extras, authority, provider, syncResult);
  }
 } catch (OperationCanceledException e) {
 }
      }

 private Uri asSyncAdapter(Uri uri, String account, String accountType) {
  return uri.buildUpon()
    .appendQueryParameter(
      CalendarContract.CALLER_IS_SYNCADAPTER, "true")
    .appendQueryParameter(Calendars.ACCOUNT_NAME, account)
    .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType)
    .build();
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  IBinder ret = null;
  ret = getSyncAdapter().getSyncAdapterBinder();
  return ret;
 }

 private SyncAdapterImpl getSyncAdapter() {
  if (sSyncAdapter == null)
   sSyncAdapter = new SyncAdapterImpl(this);
  return sSyncAdapter;
 }

 private static void performSync(Context context, Account account,
   Bundle extras, String authority, ContentProviderClient provider,
   SyncResult syncResult) throws OperationCanceledException {

  Log.i("SERVICE", "Calendar Service Start");
 }
}

使用您的帐户名称创建您自己的日历

public long CreateCalendar(Account account) {

 Log.i("CALENDAR CREATED", "Calendar With by Account Name");
 ContentResolver cr = context.getContentResolver();
 ContentValues values = new ContentValues();
 values.put(Calendars.ACCOUNT_NAME, account.name);
 values.put(CalendarContract.Calendars.ACCOUNT_TYPE,
   CalendarContract.ACCOUNT_TYPE_LOCAL);
 values.put(Calendars.NAME, account.name);
 values.put(Calendars.CALENDAR_DISPLAY_NAME, account.name);
 values.put(Calendars.CALENDAR_COLOR, 0xFFFFFFFF);
 values.put(Calendars.CALENDAR_ACCESS_LEVEL,
   Calendars.CAL_ACCESS_OWNER);
 values.put(Calendars.OWNER_ACCOUNT, account.name);
 values.put(Calendars.SYNC_EVENTS, 1);
 values.put(Calendars.VISIBLE, 1);
 values.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, TimeZone
   .getDefault().getID());

 Uri creationUri = asSyncAdapter(Calendars.CONTENT_URI,
   account.name, account.type);

 Uri created = cr.insert(creationUri, values);
 long cal_id = Long.parseLong(created.getLastPathSegment());
 return cal_id;
}

在您创建的日历中创建事件

public void SyncEvent(long id, int meeting_id, String EventName,
   String Stime, String Etime, String Description) {

 Calendar cal = Calendar.getInstance();
 cal.setTimeZone(TimeZone.getTimeZone("GMT-1"));
 Date dt = null;
 Date dt1 = null;
 try {
  dt = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(Stime);
  dt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(Etime);

  Calendar beginTime = Calendar.getInstance();
  cal.setTime(dt);

  // beginTime.set(2013, 7, 25, 7, 30);
  beginTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
  cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY),
  cal.get(Calendar.MINUTE));

  Calendar endTime = Calendar.getInstance();
  cal.setTime(dt1);

  // endTime.set(2013, 7, 25, 14, 30);
  // endTime.set(year, month, day, hourOfDay, minute);
  endTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
  cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY),
  cal.get(Calendar.MINUTE));

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

  values.put(Events.DTSTART, beginTime.getTimeInMillis());
  values.put(Events.DTEND, endTime.getTimeInMillis());
  values.put(Events.TITLE, EventName);
  values.put(Events.DESCRIPTION, Description);
  values.put(Events.CALENDAR_ID, id);
  // values.put(Events._ID, meeting_id);
  values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());

  Uri uri = cr.insert(Events.CONTENT_URI, values);
  long eventID = Long.parseLong(uri.getLastPathSegment());
 } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

检查设备中是否存在日历

public int queryCalendar(Account account) {

 Cursor cur = null;
 ContentResolver cr = this.mContext.getContentResolver();
 Uri uri = Calendars.CONTENT_URI;
 String selection = "((" + Calendars.ACCOUNT_NAME + " = '"
     + account.name + "'))";
 cur = cr.query(uri, CALENDAR_PROJECTION, selection, null, null);
 while (cur.moveToNext()) {
  return cur.getInt(0);
 }
 return 0;
}

检查事件是否在日历中

public boolean isEventInCal(Context context, String cal_meeting_id) {

 Cursor cursor = context.getContentResolver().query(
 Uri.parse("content://com.android.calendar/events"),
   new String[] { "_id" }, " _id = ? ",
   new String[] { cal_meeting_id }, null);

       if (cursor.moveToFirst()) {
  return true;
 }
 return false;
}

获取设备中日历中所有已注册的事件[所有日历]

public boolean all_Events(Context context) {

        boolean flag = false;
 Cursor cursor = context.getContentResolver().query(
  Uri.parse("content://com.android.calendar/events"),
   new String[] { "calendar_id", "title", "description",
     "dtstart", "dtend", "eventLocation", "_id",
     "allDay", "duration" }, null, null, null);

 if (cursor.moveToFirst()) {
 do {
           //all the EVENTS Will be fetched From Here Which 
           //Are registered under DEVICE
  } while (cursor.moveToNext());
    }
 return flag;
}

从您自己创建的日历中删除事件

public void event_Delete(long eventID) {

 // ContentResolver cr = this.mContext.getContentResolver();
  // ContentValues values = new ContentValues();
  Uri deleteUri = null;
  deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID);
  int rows = this.mContext.getContentResolver().delete(deleteUri,
   null, null);
  Log.i("Rows deleted: ", "" + rows);
 }
4

0 回答 0