List of usage examples for android.text.format DateUtils DAY_IN_MILLIS
long DAY_IN_MILLIS
To view the source code for android.text.format DateUtils DAY_IN_MILLIS.
Click Source Link
From source file:com.android.exchange.EasAccountService.java
/** * Performs FolderSync//from w ww. ja v a2 s.com * * @throws IOException * @throws EasParserException */ public void sync() throws IOException, EasParserException { // Check that the account's mailboxes are consistent MailboxUtilities.checkMailboxConsistency(mContext, mAccount.mId); // Initialize exit status to success try { if (mAccount.mSyncKey == null) { mAccount.mSyncKey = "0"; userLog("Account syncKey INIT to 0"); ContentValues cv = new ContentValues(); cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey); mAccount.update(mContext, cv); } boolean firstSync = mAccount.mSyncKey.equals("0"); if (firstSync) { userLog("Initial FolderSync"); } // When we first start up, change all mailboxes to push. ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING, new String[] { Long.toString(mAccount.mId) }) > 0) { ExchangeService.kick("change ping boxes to push"); } // Determine our protocol version, if we haven't already and save it in the Account // Also re-check protocol version at least once a day (in case of upgrade) if (mAccount.mProtocolVersion == null || firstSync || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DateUtils.DAY_IN_MILLIS)) { userLog("Determine EAS protocol version"); EasResponse resp = sendHttpClientOptions(); try { int code = resp.getStatus(); userLog("OPTIONS response: ", code); if (code == HttpStatus.SC_OK) { Header header = resp.getHeader("MS-ASProtocolCommands"); userLog(header.getValue()); header = resp.getHeader("ms-asprotocolversions"); try { setupProtocolVersion(this, header); } catch (MessagingException e) { // Since we've already validated, this can't really happen // But if it does, we'll rethrow this... throw new IOException(e); } // Save the protocol version cv.clear(); // Save the protocol version in the account; if we're using 12.0 or greater, // set the flag for support of SmartForward cv.put(Account.PROTOCOL_VERSION, mProtocolVersion); if (mProtocolVersionDouble >= 12.0) { cv.put(Account.FLAGS, mAccount.mFlags | Account.FLAGS_SUPPORTS_SMART_FORWARD | Account.FLAGS_SUPPORTS_SEARCH | Account.FLAGS_SUPPORTS_GLOBAL_SEARCH); } mAccount.update(mContext, cv); cv.clear(); // Save the sync time of the account mailbox to current time cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); mMailbox.update(mContext, cv); } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) { // Cause this to re-run throw new IOException("Will retry after a brief hold..."); } else if (resp.isProvisionError()) { throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING); } else if (resp.isAuthError()) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; return; } else { errorLog("OPTIONS command failed; throwing IOException"); throw new IOException(); } } finally { resp.close(); } } // Change all pushable boxes to push when we start the account mailbox if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) { cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] { Long.toString(mAccount.mId) }) > 0) { userLog("Push account; set pushable boxes to push..."); } } while (!isStopped()) { // If we're not allowed to sync (e.g. roaming policy), leave now if (!ExchangeService.canAutoSync(mAccount)) { if (ExchangeService.onSecurityHold(mAccount)) { mExitStatus = EasSyncService.EXIT_SECURITY_FAILURE; } else { // Use backoff rules, etc. mExitStatus = EasSyncService.EXIT_IO_ERROR; } return; } userLog("Sending Account syncKey: ", mAccount.mSyncKey); Serializer s = new Serializer(); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(mAccount.mSyncKey).end().end() .done(); EasResponse resp = sendHttpClientPost("FolderSync", s.toByteArray()); try { if (isStopped()) break; int code = resp.getStatus(); if (code == HttpStatus.SC_OK) { if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); // Returns true if we need to sync again if (new FolderSyncParser(is, new AccountSyncAdapter(this)).parse()) { continue; } } } else if (resp.isProvisionError()) { throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING); } else if (resp.isAuthError()) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; return; } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) { // This will cause a retry of the FolderSync continue; } else { userLog("FolderSync response error: ", code); } } finally { resp.close(); } // Change all push/hold boxes to push cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX, new String[] { Long.toString(mAccount.mId) }) > 0) { userLog("Set push/hold boxes to push..."); } // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's // active; otherwise, clear out the key/flag. This should cause a provisioning // error on the next POST, and start the security sequence over again String key = mAccount.mSecuritySyncKey; if (!TextUtils.isEmpty(key)) { Policy policy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey); if ((policy != null) && !PolicyServiceProxy.isActive(mContext, policy)) { resetSecurityPolicies(); } } // Wait for push notifications. String threadName = Thread.currentThread().getName(); try { runPingLoop(); } catch (StaleFolderListException e) { // We break out if we get told about a stale folder list userLog("Ping interrupted; folder list requires sync..."); } catch (IllegalHeartbeatException e) { // If we're sending an illegal heartbeat, reset either the min or the max to // that heartbeat resetHeartbeats(e.mLegalHeartbeat); } finally { Thread.currentThread().setName(threadName); } } } catch (CommandStatusException e) { // If the sync error is a provisioning failure (perhaps policies changed), // let's try the provisioning procedure // Provisioning must only be attempted for the account mailbox - trying to // provision any other mailbox may result in race conditions and the // creation of multiple policy keys. int status = e.mStatus; if (CommandStatus.isNeedsProvisioning(status)) { if (!tryProvision(this)) { // Set the appropriate failure status mExitStatus = EasSyncService.EXIT_SECURITY_FAILURE; return; } } else if (CommandStatus.isDeniedAccess(status)) { mExitStatus = EasSyncService.EXIT_ACCESS_DENIED; return; } else { userLog("Unexpected status: " + CommandStatus.toString(status)); mExitStatus = EasSyncService.EXIT_EXCEPTION; } } }
From source file:net.peterkuterna.android.apps.devoxxfrsched.ui.HomeActivity.java
private void refreshPager() { final long currentTimeMillis = UIUtils.getCurrentTime(this); if (currentTimeMillis >= UIUtils.START_DAYS_IN_MILLIS[0] && currentTimeMillis < (UIUtils.START_DAYS_IN_MILLIS[UIUtils.NUMBER_DAYS - 1] + DateUtils.DAY_IN_MILLIS)) { mDuringConference = true;//from w ww . j a v a 2 s . com mFragmentManager.addOnBackStackChangedListener(this); } else { mDuringConference = false; mFragmentManager.removeOnBackStackChangedListener(this); } mTabsContainer.setVisibility(mDuringConference ? View.VISIBLE : View.GONE); mViewPager.setAdapter(mAdapter); mTabs.setAdapter(mAdapter); }
From source file:org.voidsink.anewjkuapp.fragment.CalendarFragment2.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { ArrayList<WeekViewEvent> events = mWeekViewLoader.getEvents(loader.getId()); events.clear();/*w w w. ja v a2 s.c o m*/ Account mAccount = AppUtils.getAccount(getContext()); if (mAccount != null) { // fetch calendar colors final SparseIntArray mColors = new SparseIntArray(); ContentResolver cr = getContext().getContentResolver(); Cursor cursor = cr.query(CalendarContractWrapper.Calendars.CONTENT_URI(), new String[] { CalendarContractWrapper.Calendars._ID(), CalendarContractWrapper.Calendars.CALENDAR_COLOR() }, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { int color = cursor.getInt(1); double lastContrast = ColorUtils.calculateContrast(color, mWeekView.getEventTextColor()); //Log.d(TAG, String.format("color=%d %d %d, contrast=%f", Color.red(color), Color.green(color), Color.blue(color), lastContrast)); while (lastContrast < 1.6) { float[] hsv = new float[3]; Color.colorToHSV(color, hsv); hsv[2] = Math.max(0f, hsv[2] - 0.033f); // darken color = Color.HSVToColor(hsv); lastContrast = ColorUtils.calculateContrast(color, mWeekView.getEventTextColor()); //Log.d(TAG, String.format("new color=%d %d %d, contrast=%f", Color.red(color), Color.green(color), Color.blue(color), lastContrast)); if (hsv[2] == 0) break; } mColors.put(cursor.getInt(0), color); } cursor.close(); } if (data != null) { data.moveToFirst(); data.moveToPrevious(); while (data.moveToNext()) { boolean allDay = data.getInt(CalendarUtils.COLUMN_EVENT_ALL_DAY) == 1; Calendar startTime = Calendar.getInstance(); if (allDay) { startTime.setTimeZone(TimeZone.getTimeZone("UTC")); } startTime.setTimeInMillis(data.getLong(CalendarUtils.COLUMN_EVENT_DTSTART)); Calendar endTime = Calendar.getInstance(); if (allDay) { endTime.setTimeZone(TimeZone.getTimeZone("UTC")); } endTime.setTimeInMillis(data.getLong(CalendarUtils.COLUMN_EVENT_DTEND)); if (allDay && endTime.getTimeInMillis() % DateUtils.DAY_IN_MILLIS == 0) { endTime.add(Calendar.MILLISECOND, -1); } WeekViewEvent event = new WeekViewEvent(data.getLong(CalendarUtils.COLUMN_EVENT_ID), data.getString(CalendarUtils.COLUMN_EVENT_TITLE), data.getString(CalendarUtils.COLUMN_EVENT_LOCATION), startTime, endTime, allDay); event.setColor(mColors.get(data.getInt(CalendarUtils.COLUMN_EVENT_CAL_ID))); events.add(event); } } } mWeekView.notifyDatasetChanged(); }
From source file:saschpe.birthdays.service.CalendarSyncService.java
private static ContentProviderOperation insertEvent(Context context, long calendarId, Date eventDate, int year, String title, String description, String lookupKey) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(getCalendarUri(context, CalendarContract.Events.CONTENT_URI)); Calendar calendar = Calendar.getInstance(); calendar.setTime(eventDate);//from w w w. ja va2 s. c om calendar.set(Calendar.YEAR, year); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); /* Define over entire day. * * Note: ALL_DAY is enough on original Android calendar, but some calendar apps (Business * Calendar) do not display the event if time between dtstart and dtend is 0 */ final long dtstart = calendar.getTimeInMillis(); final long dtend = dtstart + DateUtils.DAY_IN_MILLIS; builder.withValue(CalendarContract.Events.CALENDAR_ID, calendarId); builder.withValue(CalendarContract.Events.DTSTART, dtstart); builder.withValue(CalendarContract.Events.DTEND, dtend); builder.withValue(CalendarContract.Events.EVENT_TIMEZONE, Time.TIMEZONE_UTC); builder.withValue(CalendarContract.Events.ALL_DAY, 1); builder.withValue(CalendarContract.Events.TITLE, title); builder.withValue(CalendarContract.Events.DESCRIPTION, description); builder.withValue(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED); /* Enable reminders for this event * Note: Need to be explicitly set on Android < 4 to enable reminders */ builder.withValue(CalendarContract.Events.HAS_ALARM, 1); // Set availability 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 && lookupKey != null) { builder.withValue(CalendarContract.Events.CUSTOM_APP_PACKAGE, context.getPackageName()); final Uri contactLookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); builder.withValue(CalendarContract.Events.CUSTOM_APP_URI, contactLookupUri.toString()); } return builder.build(); }
From source file:biz.wiz.android.wallet.WalletApplication.java
private void backupWallet() { final Protos.Wallet.Builder builder = new WalletProtobufSerializer().walletToProto(wallet).toBuilder(); // strip redundant builder.clearTransaction();// w ww . j ava 2 s . c om builder.clearLastSeenBlockHash(); builder.setLastSeenBlockHeight(-1); builder.clearLastSeenBlockTimeSecs(); final Protos.Wallet walletProto = builder.build(); OutputStream os = null; try { os = openFileOutput(Constants.Files.WALLET_KEY_BACKUP_PROTOBUF, Context.MODE_PRIVATE); walletProto.writeTo(os); } catch (final IOException x) { log.error("problem writing key backup", x); } finally { try { os.close(); } catch (final IOException x) { // swallow } } try { final String filename = String.format(Locale.US, "%s.%02d", Constants.Files.WALLET_KEY_BACKUP_PROTOBUF, (System.currentTimeMillis() / DateUtils.DAY_IN_MILLIS) % 100l); os = openFileOutput(filename, Context.MODE_PRIVATE); walletProto.writeTo(os); } catch (final IOException x) { log.error("problem writing key backup", x); } finally { try { os.close(); } catch (final IOException x) { // swallow } } }
From source file:org.voidsink.anewjkuapp.update.ImportCalendarTask.java
@Override public Void call() throws Exception { if (mProvider == null) { return null; }//from w w w . j ava 2 s. c o m if ((ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) || (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED)) { return null; } if (!CalendarUtils.getSyncCalendar(mContext, this.mCalendarName)) { return null; } if (mShowProgress) { mUpdateNotification = new SyncNotification(mContext, R.string.notification_sync_calendar); mUpdateNotification.show(mContext.getString(R.string.notification_sync_calendar_loading, CalendarUtils.getCalendarName(mContext, this.mCalendarName))); } CalendarChangedNotification mNotification = new CalendarChangedNotification(mContext, CalendarUtils.getCalendarName(mContext, this.mCalendarName)); try { Log.d(TAG, "setup connection"); updateNotify(mContext.getString(R.string.notification_sync_connect)); if (KusssHandler.getInstance().isAvailable(mContext, AppUtils.getAccountAuthToken(mContext, mAccount), AppUtils.getAccountName(mContext, mAccount), AppUtils.getAccountPassword(mContext, mAccount))) { updateNotify(mContext.getString(R.string.notification_sync_calendar_loading, CalendarUtils.getCalendarName(mContext, this.mCalendarName))); Log.d(TAG, "loading calendar"); Calendar iCal; String kusssIdPrefix; // {{ Load calendar events from resource switch (this.mCalendarName) { case CalendarUtils.ARG_CALENDAR_EXAM: iCal = KusssHandler.getInstance().getExamIcal(mContext, mCalendarBuilder); kusssIdPrefix = "at-jku-kusss-exam-"; break; case CalendarUtils.ARG_CALENDAR_COURSE: iCal = KusssHandler.getInstance().getLVAIcal(mContext, mCalendarBuilder); kusssIdPrefix = "at-jku-kusss-coursedate-"; break; default: { Log.w(TAG, "calendar not found: " + this.mCalendarName); return null; } } if (iCal == null) { Log.w(TAG, "calendar not loaded: " + this.mCalendarName); mSyncResult.stats.numParseExceptions++; return null; } List<?> events = iCal.getComponents(Component.VEVENT); Log.d(TAG, String.format("got %d events", events.size())); updateNotify(mContext.getString(R.string.notification_sync_calendar_updating, CalendarUtils.getCalendarName(mContext, this.mCalendarName))); ArrayList<ContentProviderOperation> batch = new ArrayList<>(); // modify events: move courseId/term and lecturer to description String lineSeparator = System.getProperty("line.separator"); if (lineSeparator == null) lineSeparator = ", "; Map<String, VEvent> eventsMap = new HashMap<>(); for (Object e : events) { if (VEvent.class.isInstance(e)) { VEvent ev = ((VEvent) e); String summary = ev.getSummary().getValue().trim(); String description = ev.getDescription().getValue().trim(); Matcher courseIdTermMatcher = courseIdTermPattern.matcher(summary); // (courseId/term) if (courseIdTermMatcher.find()) { if (!description.isEmpty()) { description += lineSeparator; description += lineSeparator; } description += summary.substring(courseIdTermMatcher.start()); summary = summary.substring(0, courseIdTermMatcher.start()); } else { Matcher lecturerMatcher = lecturerPattern.matcher(summary); if (lecturerMatcher.find()) { if (!description.isEmpty()) { description += lineSeparator; description += lineSeparator; } description += summary.substring(lecturerMatcher.start()); summary = summary.substring(0, lecturerMatcher.start()); } } summary = summary.trim().replaceAll("([\\r\\n]|\\\\n)+", ", ").trim(); description = description.trim(); ev.getProperty(Property.SUMMARY).setValue(summary); ev.getProperty(Property.DESCRIPTION).setValue(description); } } // Build hash table of incoming entries for (Object e : events) { if (VEvent.class.isInstance(e)) { VEvent ev = ((VEvent) e); String uid = ev.getUid().getValue(); // compense DST eventsMap.put(uid, ev); } } String calendarId = CalendarUtils.getCalIDByName(mContext, mAccount, mCalendarName, true); if (calendarId == null) { Log.w(TAG, "calendarId not found"); return null; } String mCalendarAccountName = mAccount.name; String mCalendarAccountType = mAccount.type; try { Cursor c = mProvider.query(CalendarContractWrapper.Calendars.CONTENT_URI(), CalendarUtils.CALENDAR_PROJECTION, null, null, null); if (c != null) { while (c.moveToNext()) { if (calendarId.equals(c.getString(CalendarUtils.COLUMN_CAL_ID))) { mCalendarAccountName = c.getString(CalendarUtils.COLUMN_CAL_ACCOUNT_NAME); mCalendarAccountType = c.getString(CalendarUtils.COLUMN_CAL_ACCOUNT_TYPE); break; } } c.close(); } } catch (Exception e) { return null; } Log.d(TAG, "Fetching local entries for merge with: " + calendarId); Uri calUri = CalendarContractWrapper.Events.CONTENT_URI(); Cursor c = CalendarUtils.loadEvent(mProvider, calUri, calendarId); if (c == null) { Log.w(TAG, "selection failed"); } else { Log.d(TAG, String.format("Found %d local entries. Computing merge solution...", c.getCount())); // find stale data String eventId; String eventKusssId; String eventLocation; String eventTitle; String eventDescription; long eventDTStart; long eventDTEnd; boolean eventDirty; boolean eventDeleted; // calc date for notifiying only future changes // max update interval is 1 week long notifyFrom = new Date().getTime() - (DateUtils.DAY_IN_MILLIS * 7); while (c.moveToNext()) { mSyncResult.stats.numEntries++; eventId = c.getString(CalendarUtils.COLUMN_EVENT_ID); // Log.d(TAG, "---------"); eventKusssId = null; // get kusssId from extended properties Cursor c2 = mProvider.query(CalendarContract.ExtendedProperties.CONTENT_URI, CalendarUtils.EXTENDED_PROPERTIES_PROJECTION, CalendarContract.ExtendedProperties.EVENT_ID + " = ?", new String[] { eventId }, null); if (c2 != null) { while (c2.moveToNext()) { // String extra = ""; // for (int i = 0; i < c2.getColumnCount(); i++) { // extra = extra + i + "=" + c2.getString(i) + ";"; // } // Log.d(TAG, "Extended: " + extra); if (c2.getString(1).contains(CalendarUtils.EXTENDED_PROPERTY_NAME_KUSSS_ID)) { eventKusssId = c2.getString(2); } } c2.close(); } if (TextUtils.isEmpty(eventKusssId)) { eventKusssId = c.getString(CalendarUtils.COLUMN_EVENT_KUSSS_ID_LEGACY); } eventTitle = c.getString(CalendarUtils.COLUMN_EVENT_TITLE); Log.d(TAG, "Title: " + eventTitle); eventLocation = c.getString(CalendarUtils.COLUMN_EVENT_LOCATION); eventDescription = c.getString(CalendarUtils.COLUMN_EVENT_DESCRIPTION); eventDTStart = c.getLong(CalendarUtils.COLUMN_EVENT_DTSTART); eventDTEnd = c.getLong(CalendarUtils.COLUMN_EVENT_DTEND); eventDirty = "1".equals(c.getString(CalendarUtils.COLUMN_EVENT_DIRTY)); eventDeleted = "1".equals(c.getString(CalendarUtils.COLUMN_EVENT_DELETED)); if (eventKusssId != null && kusssIdPrefix != null && eventKusssId.startsWith(kusssIdPrefix)) { VEvent match = eventsMap.get(eventKusssId); if (match != null && !eventDeleted) { // Entry exists. Remove from entry // map to prevent insert later eventsMap.remove(eventKusssId); // update only changes after notifiyFrom if ((match.getStartDate().getDate().getTime() > notifyFrom || eventDTStart > notifyFrom) && // check to see if the entry needs to be updated ((match.getStartDate().getDate().getTime() != eventDTStart) || (match.getEndDate().getDate().getTime() != eventDTEnd) || (!match.getSummary().getValue().trim().equals(eventTitle.trim())) || (!match.getSummary().getValue().trim().equals(eventTitle.trim())) || (!match.getLocation().getValue().trim() .equals(eventLocation.trim())) || (!match.getDescription().getValue().trim() .equals(eventDescription.trim())))) { Uri existingUri = calUri.buildUpon().appendPath(eventId).build(); // Update existing record Log.d(TAG, "Scheduling update: " + existingUri + " dirty=" + eventDirty); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValues(getContentValuesFromEvent(match)).build()); mSyncResult.stats.numUpdates++; mNotification.addUpdate(getEventString(mContext, match)); } else { mSyncResult.stats.numSkippedEntries++; } } else { if (eventDTStart > (mSyncFromNow - DateUtils.DAY_IN_MILLIS)) { // Entry doesn't exist. Remove only newer events from the database. Uri deleteUri = calUri.buildUpon().appendPath(eventId).build(); Log.d(TAG, "Scheduling delete: " + deleteUri); // notify only future changes if (eventDTStart > notifyFrom && !eventDeleted) { mNotification.addDelete(AppUtils.getEventString(mContext, eventDTStart, eventDTEnd, eventTitle, false)); } batch.add(ContentProviderOperation.newDelete(deleteUri).build()); mSyncResult.stats.numDeletes++; } else { mSyncResult.stats.numSkippedEntries++; } } } else { Log.i(TAG, "Event UID not set, ignore event: uid=" + eventKusssId + " dirty=" + eventDirty + " title=" + eventTitle); } } c.close(); Log.d(TAG, String.format("Cursor closed, %d events left", eventsMap.size())); updateNotify(mContext.getString(R.string.notification_sync_calendar_adding, CalendarUtils.getCalendarName(mContext, this.mCalendarName))); // Add new items for (VEvent v : eventsMap.values()) { if (v.getUid().getValue().startsWith(kusssIdPrefix)) { // notify only future changes if (v.getStartDate().getDate().getTime() > notifyFrom) { mNotification.addInsert(getEventString(mContext, v)); } Builder builder = ContentProviderOperation .newInsert(CalendarContractWrapper.Events.CONTENT_URI()); builder.withValue(CalendarContractWrapper.Events.CALENDAR_ID(), calendarId) .withValues(getContentValuesFromEvent(v)) .withValue(CalendarContractWrapper.Events.EVENT_TIMEZONE(), TimeZone.getDefault().getID()); if (mCalendarName.equals(CalendarUtils.ARG_CALENDAR_EXAM)) { builder.withValue(CalendarContractWrapper.Events.AVAILABILITY(), CalendarContractWrapper.Events.AVAILABILITY_BUSY()); } else { builder.withValue(CalendarContractWrapper.Events.AVAILABILITY(), CalendarContractWrapper.Events.AVAILABILITY_FREE()); } builder.withValue(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_TENTATIVE); builder.withValue(CalendarContract.Events.HAS_ALARM, "0"); builder.withValue(CalendarContract.Events.HAS_ATTENDEE_DATA, "0"); builder.withValue(CalendarContract.Events.HAS_EXTENDED_PROPERTIES, "1"); ContentProviderOperation op = builder.build(); Log.d(TAG, "Scheduling insert: " + v.getUid().getValue()); batch.add(op); int eventIndex = batch.size() - 1; // add kusssid as extendet property batch.add(ContentProviderOperation .newInsert(KusssContentContract.asEventSyncAdapter( CalendarContract.ExtendedProperties.CONTENT_URI, mAccount.name, mAccount.type)) .withValueBackReference(CalendarContract.ExtendedProperties.EVENT_ID, eventIndex) .withValue(CalendarContract.ExtendedProperties.NAME, CalendarUtils.EXTENDED_PROPERTY_NAME_KUSSS_ID) .withValue(CalendarContract.ExtendedProperties.VALUE, v.getUid().getValue()) .build()); // add location extra for google maps batch.add(ContentProviderOperation .newInsert(KusssContentContract.asEventSyncAdapter( CalendarContract.ExtendedProperties.CONTENT_URI, mAccount.name, mAccount.type)) .withValueBackReference(CalendarContract.ExtendedProperties.EVENT_ID, eventIndex) .withValue(CalendarContract.ExtendedProperties.NAME, CalendarUtils.EXTENDED_PROPERTY_LOCATION_EXTRA) .withValue(CalendarContract.ExtendedProperties.VALUE, getLocationExtra(v)) .build()); mSyncResult.stats.numInserts++; } else { mSyncResult.stats.numSkippedEntries++; } } if (batch.size() > 0) { updateNotify(mContext.getString(R.string.notification_sync_calendar_saving, CalendarUtils.getCalendarName(mContext, this.mCalendarName))); Log.d(TAG, "Applying batch update"); mProvider.applyBatch(batch); Log.d(TAG, "Notify resolver"); mResolver.notifyChange(calUri.buildUpon().appendPath(calendarId).build(), // URI // where // data // was // modified null, // No local observer false); // IMPORTANT: Do not sync to // network } else { Log.w(TAG, "No batch operations found! Do nothing"); } } KusssHandler.getInstance().logout(mContext); } else { mSyncResult.stats.numAuthExceptions++; } } catch (Exception e) { Analytics.sendException(mContext, e, true); Log.e(TAG, "import calendar failed", e); } if (mUpdateNotification != null) { mUpdateNotification.cancel(); } mNotification.show(); if (mReleaseProvider) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mProvider.close(); } else { mProvider.release(); } } return null; }
From source file:com.just.agentweb.AgentWebUtils.java
static int clearCacheFolder(final File dir, final int numDays) { int deletedFiles = 0; if (dir != null) { Log.i("Info", "dir:" + dir.getAbsolutePath()); }/* w w w .j a v a 2 s.c o m*/ if (dir != null && dir.isDirectory()) { try { for (File child : dir.listFiles()) { //first delete subdirectories recursively if (child.isDirectory()) { deletedFiles += clearCacheFolder(child, numDays); } //then delete the files and subdirectories in this dir //only empty directories can be deleted, so subdirs have been done first if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) { Log.i(TAG, "file name:" + child.getName()); if (child.delete()) { deletedFiles++; } } } } catch (Exception e) { Log.e("Info", String.format("Failed to clean the cache, result %s", e.getMessage())); } } return deletedFiles; }
From source file:org.voidsink.anewjkuapp.calendar.CalendarUtils.java
private static boolean deleteKusssEvents(Context context, String calId) { if (calId != null) { ContentProviderClient provider = context.getContentResolver() .acquireContentProviderClient(CalendarContractWrapper.Events.CONTENT_URI()); if (provider == null) { return false; }/*w w w. j ava 2s .com*/ try { Uri calUri = CalendarContractWrapper.Events.CONTENT_URI(); Cursor c = loadEvent(provider, calUri, calId); if (c != null) { try { ArrayList<ContentProviderOperation> batch = new ArrayList<>(); long deleteFrom = new Date().getTime() - DateUtils.DAY_IN_MILLIS; while (c.moveToNext()) { long eventDTStart = c.getLong(CalendarUtils.COLUMN_EVENT_DTSTART); if (eventDTStart > deleteFrom) { String eventId = c.getString(COLUMN_EVENT_ID); // Log.d(TAG, "---------"); String eventKusssId = null; // get kusssId from extended properties Cursor c2 = provider.query(CalendarContract.ExtendedProperties.CONTENT_URI, CalendarUtils.EXTENDED_PROPERTIES_PROJECTION, CalendarContract.ExtendedProperties.EVENT_ID + " = ?", new String[] { eventId }, null); if (c2 != null) { while (c2.moveToNext()) { if (c2.getString(1).contains(EXTENDED_PROPERTY_NAME_KUSSS_ID)) { eventKusssId = c2.getString(2); } } c2.close(); } if (TextUtils.isEmpty(eventKusssId)) { eventKusssId = c.getString(COLUMN_EVENT_KUSSS_ID_LEGACY); } if (!TextUtils.isEmpty(eventKusssId)) { if (eventKusssId.startsWith("at-jku-kusss-exam-") || eventKusssId.startsWith("at-jku-kusss-coursedate-")) { Uri deleteUri = calUri.buildUpon().appendPath(eventId).build(); Log.d(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } } } if (batch.size() > 0) { Log.d(TAG, "Applying batch update"); provider.applyBatch(batch); Log.d(TAG, "Notify resolver"); } else { Log.w(TAG, "No batch operations found! Do nothing"); } } catch (RemoteException | OperationApplicationException e) { Analytics.sendException(context, e, true); return false; } } } finally { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { provider.close(); } else { provider.release(); } } return false; } return true; }
From source file:com.android.deskclock.Utils.java
public static boolean isAlarmWithin24Hours(AlarmInstance alarmInstance) { final Calendar nextAlarmTime = alarmInstance.getAlarmTime(); final long nextAlarmTimeMillis = nextAlarmTime.getTimeInMillis(); return nextAlarmTimeMillis - System.currentTimeMillis() <= DateUtils.DAY_IN_MILLIS; }
From source file:org.dmfs.tasks.notification.NotificationActionUtils.java
/** * Returns a string representation for the time, with a relative date and an absolute time */// www .j a v a 2 s.c o m public static String formatTime(Context context, Time time) { Time now = new Time(); now.setToNow(); String dateString; if (time.allDay) { Time allDayNow = new Time("UTC"); allDayNow.set(now.monthDay, now.month, now.year); dateString = DateUtils.getRelativeTimeSpanString(time.toMillis(false), allDayNow.toMillis(false), DateUtils.DAY_IN_MILLIS).toString(); } else { dateString = DateUtils .getRelativeTimeSpanString(time.toMillis(false), now.toMillis(false), DateUtils.DAY_IN_MILLIS) .toString(); } // return combined date and time String timeString = new DateFormatter(context).format(time, DateFormatContext.NOTIFICATION_VIEW_TIME); return new StringBuilder().append(dateString).append(", ").append(timeString).toString(); }