6

ここに画像の説明を入力

自分のアカウントに独自の sync_calendar 機能を設定する方法と、自分のイベントを同期する方法を示しました。

マニフェストでカレンダーの読み取りと書き込みの許可を与える

<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