List of usage examples for android.text.format DateUtils isToday
public static boolean isToday(long when)
From source file:com.woollysammoth.nubit_android_wallet.ui.TransactionsListFragment.java
private void handleTransactionClick(@Nonnull final Transaction tx) { activity.startActionMode(new ActionMode.Callback() { private Address address; private byte[] serializedTx; private static final int SHOW_QR_THRESHOLD_BYTES = 2500; @Override/*from w w w . j av a2 s. c om*/ public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { final MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.wallet_transactions_context, menu); return true; } @Override public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { try { final Date time = tx.getUpdateTime(); final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity); final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity); mode.setTitle(time != null ? (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time)) + ", " + timeFormat.format(time) : null); final BigInteger value = tx.getValue(wallet); final boolean sent = value.signum() < 0; address = sent ? WalletUtils.getFirstToAddress(tx) : WalletUtils.getFirstFromAddress(tx); final String label; if (tx.isCoinBase()) label = getString(R.string.wallet_transactions_fragment_coinbase); else if (address != null) label = AddressBookProvider.resolveLabel(activity, address.toString()); else label = "?"; final String prefix = getString(sent ? R.string.symbol_to : R.string.symbol_from) + " "; if (tx.getPurpose() != Purpose.KEY_ROTATION) mode.setSubtitle(label != null ? prefix + label : WalletUtils.formatAddress(prefix, address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE)); else mode.setSubtitle(null); menu.findItem(R.id.wallet_transactions_context_edit_address).setVisible(address != null); serializedTx = tx.unsafeNubitSerialize(); menu.findItem(R.id.wallet_transactions_context_show_qr) .setVisible(serializedTx.length < SHOW_QR_THRESHOLD_BYTES); Nfc.publishMimeObject(nfcManager, activity, Constants.MIMETYPE_TRANSACTION, serializedTx); return true; } catch (final ScriptException x) { return false; } } @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { switch (item.getItemId()) { case R.id.wallet_transactions_context_edit_address: handleEditAddress(tx); mode.finish(); return true; case R.id.wallet_transactions_context_show_qr: handleShowQr(); mode.finish(); return true; case R.id.wallet_transactions_context_browse: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.EXPLORE_BASE_URL + "tx/" + tx.getHashAsString()))); mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(final ActionMode mode) { Nfc.unpublish(nfcManager, activity); } private void handleEditAddress(@Nonnull final Transaction tx) { EditAddressBookEntryFragment.edit(getFragmentManager(), address.toString()); } private void handleShowQr() { final int size = (int) (384 * getResources().getDisplayMetrics().density); final Bitmap qrCodeBitmap = Qr.bitmap(Qr.encodeCompressBinary(serializedTx), size); BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); }
From source file:com.matthewmitchell.nubits_android_wallet.ui.TransactionsListFragment.java
private void handleTransactionClick(@Nonnull final Transaction tx) { activity.startActionMode(new ActionMode.Callback() { private Address address; private byte[] serializedTx; private static final int SHOW_QR_THRESHOLD_BYTES = 2500; @Override/*from ww w . ja va2 s.c o m*/ public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { final MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.wallet_transactions_context, menu); return true; } @Override public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { try { final Date time = tx.getUpdateTime(); final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity); final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity); mode.setTitle(time != null ? (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time)) + ", " + timeFormat.format(time) : null); final BigInteger value = tx.getValue(wallet); final boolean sent = value.signum() < 0; address = sent ? WalletUtils.getFirstToAddress(tx) : WalletUtils.getFirstFromAddress(tx); final String label; if (tx.isCoinBase()) label = getString(R.string.wallet_transactions_fragment_coinbase); else if (address != null) label = AddressBookProvider.resolveLabel(activity, address.toString()); else label = "?"; final String prefix = getString(sent ? R.string.symbol_to : R.string.symbol_from) + " "; if (tx.getPurpose() != Purpose.KEY_ROTATION) mode.setSubtitle(label != null ? prefix + label : WalletUtils.formatAddress(prefix, address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE)); else mode.setSubtitle(null); menu.findItem(R.id.wallet_transactions_context_edit_address).setVisible(address != null); serializedTx = tx.unsafeNubitsSerialize(); menu.findItem(R.id.wallet_transactions_context_show_qr) .setVisible(serializedTx.length < SHOW_QR_THRESHOLD_BYTES); Nfc.publishMimeObject(nfcManager, activity, Constants.MIMETYPE_TRANSACTION, serializedTx); return true; } catch (final ScriptException x) { return false; } } @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { switch (item.getItemId()) { case R.id.wallet_transactions_context_edit_address: handleEditAddress(tx); mode.finish(); return true; case R.id.wallet_transactions_context_show_qr: handleShowQr(); mode.finish(); return true; case R.id.wallet_transactions_context_browse: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.EXPLORE_BASE_URL + "tx/" + tx.getHashAsString()))); mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(final ActionMode mode) { Nfc.unpublish(nfcManager, activity); } private void handleEditAddress(@Nonnull final Transaction tx) { EditAddressBookEntryFragment.edit(getFragmentManager(), address.toString()); } private void handleShowQr() { final int size = (int) (384 * getResources().getDisplayMetrics().density); final Bitmap qrCodeBitmap = Qr.bitmap(Qr.encodeCompressBinary(serializedTx), size); BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); }
From source file:com.hivewallet.androidclient.wallet.ui.TransactionsListFragment.java
private void handleTransactionClick(@Nonnull final Transaction tx) { activity.startActionMode(new ActionMode.Callback() { private Address address; private byte[] serializedTx; private static final int SHOW_QR_THRESHOLD_BYTES = 2500; @Override//from w w w. j a v a 2 s. c om public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { final MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.wallet_transactions_context, menu); return true; } @Override public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { try { final Date time = tx.getUpdateTime(); final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity); final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity); mode.setTitle(time != null ? (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time)) + ", " + timeFormat.format(time) : null); final BigInteger value = tx.getValue(wallet); final boolean sent = value.signum() < 0; address = sent ? WalletUtils.getFirstToAddress(tx) : WalletUtils.getFirstFromAddress(tx); final String label; if (tx.isCoinBase()) label = getString(R.string.wallet_transactions_fragment_coinbase); else if (address != null) label = AddressBookProvider.resolveLabel(activity, address.toString()); else label = "?"; final String prefix = getString(sent ? R.string.symbol_to : R.string.symbol_from) + " "; if (tx.getPurpose() != Purpose.KEY_ROTATION) mode.setSubtitle(label != null ? prefix + label : WalletUtils.formatAddress(prefix, address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE)); else mode.setSubtitle(null); menu.findItem(R.id.wallet_transactions_context_edit_address).setVisible(address != null); serializedTx = tx.unsafeBitcoinSerialize(); menu.findItem(R.id.wallet_transactions_context_show_qr) .setVisible(serializedTx.length < SHOW_QR_THRESHOLD_BYTES); Nfc.publishMimeObject(nfcManager, activity, Constants.MIMETYPE_TRANSACTION, serializedTx); return true; } catch (final ScriptException x) { return false; } } @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { switch (item.getItemId()) { case R.id.wallet_transactions_context_edit_address: handleEditAddress(tx); mode.finish(); return true; case R.id.wallet_transactions_context_show_qr: handleShowQr(); mode.finish(); return true; case R.id.wallet_transactions_context_browse: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.EXPLORE_BASE_URL + "tx/" + tx.getHashAsString()))); mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(final ActionMode mode) { Nfc.unpublish(nfcManager, activity); } private void handleEditAddress(@Nonnull final Transaction tx) { EditAddressBookEntryFragment.edit(getFragmentManager(), address.toString()); } private void handleShowQr() { final int size = (int) (384 * getResources().getDisplayMetrics().density); final Bitmap qrCodeBitmap = Qr.bitmap(Qr.encodeCompressBinary(serializedTx), size); BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); }
From source file:com.android.dialer.calllog.PhoneCallDetailsHelper.java
/** * Get the granular version of the call date. See {@link #getGranularDateTime(PhoneCallDetails)} *//*from w ww . ja v a2 s .co m*/ private String getGranularDate(long date) { if (DateUtils.isToday(date)) { return mResources.getString(R.string.voicemailCallLogToday); } return DateUtils.formatDateTime(mContext, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | (shouldShowYear(date) ? DateUtils.FORMAT_SHOW_YEAR : DateUtils.FORMAT_NO_YEAR)); }
From source file:org.ohmage.triggers.base.TriggerBase.java
public boolean hasTriggeredToday(Context context, int trigId) { Log.i(DEBUG_TAG, "TriggerBase: hasTriggeredToday(" + trigId + ")"); long trigTS = getTriggerLatestTimeStamp(context, trigId); if (trigTS != TriggerRunTimeDesc.INVALID_TIMESTAMP) { return DateUtils.isToday(trigTS); }//from ww w .j a v a 2 s . c om return false; }
From source file:dentex.youtube.downloader.YTD.java
public static void autoUpdate() { long storedTime = settings.getLong("time", 0); // for release //long storedTime = 10000; // dev test: forces auto update boolean shouldCheckForUpdate = !DateUtils.isToday(storedTime); Utils.logger("i", "shouldCheckForUpdate: " + shouldCheckForUpdate, DEBUG_TAG); if (shouldCheckForUpdate) { Intent intent = new Intent(ctx, AutoUpgradeApkService.class); ctx.startService(intent);/*from w w w .java 2 s .com*/ } long time = System.currentTimeMillis(); if (settings.edit().putLong("time", time).commit()) Utils.logger("i", "time written in prefs", DEBUG_TAG); }
From source file:org.ohmage.reminders.base.TriggerBase.java
public boolean hasTriggeredToday(Context context, int trigId) { Log.v(TAG, "TriggerBase: hasTriggeredToday(" + trigId + ")"); long trigTS = getTriggerLatestTimeStamp(context, trigId); if (trigTS != TriggerRunTimeDesc.INVALID_TIMESTAMP) { return DateUtils.isToday(trigTS); }/*from w w w . j a va2 s . com*/ return false; }
From source file:com.gdgdevfest.android.apps.devfestbcn.ui.MapFragment.java
/** * Create an {@link AsyncQueryHandler} for use with the * {@link MapInfoWindowAdapter}.// w w w . j a va2 s.c o m */ private AsyncQueryHandler createInfowindowHandler(ContentResolver contentResolver) { return new AsyncQueryHandler(contentResolver) { StringBuilder mBuffer = new StringBuilder(); Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { MarkerModel model = mMarkers.get(cookie); mInfoAdapter.clearData(); if (model == null || cursor == null) { // query did not complete or incorrect data was loaded return; } final long time = UIUtils.getCurrentTime(getActivity()); switch (token) { case SessionAfterQuery._TOKEN: { extractSession(cursor, model, time); } break; case SandboxCompaniesAtQuery._TOKEN: { extractSandbox(cursor, model, time); } } // update the displayed window model.marker.showInfoWindow(); } private void extractSandbox(Cursor cursor, MarkerModel model, long time) { // get tracks data from cache: icon and color TrackModel track = mTracks.get(model.track); int color = (track != null) ? track.color : 0; int iconResId = 0; if (track != null) { iconResId = getResources().getIdentifier("track_" + ParserUtils.sanitizeId(track.name), "drawable", getActivity().getPackageName()); } if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); StringBuilder sb = new StringBuilder(); int count = 0; final int maxCompaniesDisplay = getResources() .getInteger(R.integer.sandbox_company_list_max_display); while (!cursor.isAfterLast() && count < maxCompaniesDisplay) { if (sb.length() > 0) { sb.append(", "); } sb.append(cursor.getString(SandboxCompaniesAtQuery.COMPANY_NAME)); count++; cursor.moveToNext(); } if (count >= maxCompaniesDisplay && !cursor.isAfterLast()) { // Additional sandbox companies to display sb.append(", …"); } mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, sb.length() > 0 ? sb.toString() : null); } else { // No active sandbox companies mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, null); } model.marker.showInfoWindow(); } private static final long SHOW_UPCOMING_TIME = 24 * 60 * 60 * 1000; // 24 hours private void extractSession(Cursor cursor, MarkerModel model, long time) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); String currentTitle = null; String nextTitle = null; String nextTime = null; final long blockStart = cursor.getLong(SessionAfterQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionAfterQuery.BLOCK_END); boolean inProgress = time >= blockStart && time <= blockEnd; if (inProgress) { // A session is running, display its name and optionally // the next session currentTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE); //move to the next entry cursor.moveToNext(); } if (!cursor.isAfterLast()) { //There is a session coming up next, display only it if it's within 24 hours of the current time final long nextStart = cursor.getLong(SessionAfterQuery.BLOCK_START); if (nextStart < time + SHOW_UPCOMING_TIME) { nextTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE); mBuffer.setLength(0); boolean showWeekday = !DateUtils.isToday(blockStart) && !UIUtils.isSameDayDisplay(UIUtils.getCurrentTime(getActivity()), blockStart, getActivity()); nextTime = DateUtils.formatDateRange(getActivity(), mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME | (showWeekday ? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY : 0), PrefUtils.getDisplayTimeZone(getActivity()).getID()).toString(); } } // populate the info window adapter mInfoAdapter.setSessionData(model.marker, model.label, currentTitle, nextTitle, nextTime, inProgress); } else { // No entries, display name of room only mInfoAdapter.setMarker(model.marker, model.label); } } }; }
From source file:com.android.calendar.alerts.AlertService.java
/** * Processes the query results and bucketizes the alerts. * * @param highPriorityEvents This will contain future events, and concurrent events * that started recently (less than the interval DEPRIORITIZE_GRACE_PERIOD_MS). * @param mediumPriorityEvents This will contain concurrent events that started * more than DEPRIORITIZE_GRACE_PERIOD_MS ago. * @param lowPriorityEvents Will contain events that have ended. * @return Returns the number of new alerts to fire. If this is 0, it implies * a quiet update./*w w w . j a v a 2 s .c om*/ */ static int processQuery(final Cursor alertCursor, final Context context, final long currentTime, ArrayList<NotificationInfo> highPriorityEvents, ArrayList<NotificationInfo> mediumPriorityEvents, ArrayList<NotificationInfo> lowPriorityEvents) { // Experimental reminder setting to only remind for events that have // been responded to with "yes" or "maybe". String skipRemindersPref = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_REMINDERS_RESPONDED, ""); // Skip no-response events if the "Skip Reminders" preference has the second option, // "If declined or not responded", is selected. // Note that by default, the first option will be selected, so this will be false. boolean remindRespondedOnly = skipRemindersPref .equals(context.getResources().getStringArray(R.array.preferences_skip_reminders_values)[1]); // Experimental reminder setting to silence reminders when they are // during the pre-defined quiet hours. boolean useQuietHours = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS, false); // Note that the start time may be either before or after the end time, // depending on whether quiet hours cross through midnight. int quietHoursStartHour = OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR; int quietHoursStartMinute = OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE; int quietHoursEndHour = OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR; int quietHoursEndMinute = OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE; if (useQuietHours) { quietHoursStartHour = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_START_HOUR, OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR); quietHoursStartMinute = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_START_MINUTE, OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE); quietHoursEndHour = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_END_HOUR, OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR); quietHoursEndMinute = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_END_MINUTE, OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE); } Time time = new Time(); ContentResolver cr = context.getContentResolver(); HashMap<Long, NotificationInfo> eventIds = new HashMap<Long, NotificationInfo>(); int numFired = 0; try { while (alertCursor.moveToNext()) { final long alertId = alertCursor.getLong(ALERT_INDEX_ID); final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID); final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES); final String eventName = alertCursor.getString(ALERT_INDEX_TITLE); final String description = alertCursor.getString(ALERT_INDEX_DESCRIPTION); final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION); final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS); final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED; final boolean responded = status != Attendees.ATTENDEE_STATUS_NONE && status != Attendees.ATTENDEE_STATUS_INVITED; final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN); final long endTime = alertCursor.getLong(ALERT_INDEX_END); final Uri alertUri = ContentUris.withAppendedId(CalendarAlerts.CONTENT_URI, alertId); final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME); boolean forceQuiet = false; if (useQuietHours) { // Quiet hours have been set. time.set(alarmTime); // Check whether the alarm will fire after the quiet hours // start time and/or before the quiet hours end time. boolean alarmAfterQuietHoursStart = (time.hour > quietHoursStartHour || (time.hour == quietHoursStartHour && time.minute >= quietHoursStartMinute)); boolean alarmBeforeQuietHoursEnd = (time.hour < quietHoursEndHour || (time.hour == quietHoursEndHour && time.minute <= quietHoursEndMinute)); // Check if quiet hours crosses through midnight, iff: // start hour is after end hour, or // start hour is equal to end hour, and start minute is // after end minute. // i.e. 22:30 - 06:45; 12:45 - 12:00 // 01:05 - 10:30; 05:00 - 05:30 boolean quietHoursCrossesMidnight = quietHoursStartHour > quietHoursEndHour || (quietHoursStartHour == quietHoursEndHour && quietHoursStartMinute > quietHoursEndMinute); if (quietHoursCrossesMidnight) { // Quiet hours crosses midnight. Alarm should be quiet // if it's after start time OR before end time. if (alarmAfterQuietHoursStart || alarmBeforeQuietHoursEnd) { forceQuiet = true; } } else { // Quiet hours doesn't cross midnight. Alarm should be // quiet if it's after start time AND before end time. if (alarmAfterQuietHoursStart && alarmBeforeQuietHoursEnd) { forceQuiet = true; } } } int state = alertCursor.getInt(ALERT_INDEX_STATE); final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0; // Use app local storage to keep track of fired alerts to fix problem of multiple // installed calendar apps potentially causing missed alarms. boolean newAlertOverride = false; if (AlertUtils.BYPASS_DB && ((currentTime - alarmTime) / MINUTE_MS < 1)) { // To avoid re-firing alerts, only fire if alarmTime is very recent. Otherwise // we can get refires for non-dismissed alerts after app installation, or if the // SharedPrefs was cleared too early. This means alerts that were timed while // the phone was off may show up silently in the notification bar. boolean alreadyFired = AlertUtils.hasAlertFiredInSharedPrefs(context, eventId, beginTime, alarmTime); if (!alreadyFired) { newAlertOverride = true; } } if (DEBUG) { StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("alertCursor result: alarmTime:").append(alarmTime).append(" alertId:") .append(alertId).append(" eventId:").append(eventId).append(" state: ").append(state) .append(" minutes:").append(minutes).append(" declined:").append(declined) .append(" responded:").append(responded).append(" beginTime:").append(beginTime) .append(" endTime:").append(endTime).append(" allDay:").append(allDay) .append(" alarmTime:").append(alarmTime).append(" forceQuiet:").append(forceQuiet); if (AlertUtils.BYPASS_DB) { msgBuilder.append(" newAlertOverride: " + newAlertOverride); } Log.d(TAG, msgBuilder.toString()); } ContentValues values = new ContentValues(); int newState = -1; boolean newAlert = false; // Uncomment for the behavior of clearing out alerts after the // events ended. b/1880369 // // if (endTime < currentTime) { // newState = CalendarAlerts.DISMISSED; // } else // Remove declined events boolean sendAlert = !declined; // Check for experimental reminder settings. if (remindRespondedOnly) { // If the experimental setting is turned on, then only send // the alert if you've responded to the event. sendAlert = sendAlert && responded; } if (sendAlert) { if (state == CalendarAlerts.STATE_SCHEDULED || newAlertOverride) { newState = CalendarAlerts.STATE_FIRED; numFired++; // If quiet hours are forcing the alarm to be silent, // keep newAlert as false so it will not make noise. if (!forceQuiet) { newAlert = true; } // Record the received time in the CalendarAlerts table. // This is useful for finding bugs that cause alarms to be // missed or delayed. values.put(CalendarAlerts.RECEIVED_TIME, currentTime); } } else { newState = CalendarAlerts.STATE_DISMISSED; } // Update row if state changed if (newState != -1) { values.put(CalendarAlerts.STATE, newState); state = newState; if (AlertUtils.BYPASS_DB) { AlertUtils.setAlertFiredInSharedPrefs(context, eventId, beginTime, alarmTime); } } if (state == CalendarAlerts.STATE_FIRED) { // Record the time posting to notification manager. // This is used for debugging missed alarms. values.put(CalendarAlerts.NOTIFY_TIME, currentTime); } // Write row to if anything changed if (values.size() > 0) cr.update(alertUri, values, null, null); if (state != CalendarAlerts.STATE_FIRED) { continue; } // TODO: Prefer accepted events in case of ties. NotificationInfo newInfo = new NotificationInfo(eventName, location, description, beginTime, endTime, eventId, allDay, newAlert); // Adjust for all day events to ensure the right bucket. Don't use the 1/4 event // duration grace period for these. long beginTimeAdjustedForAllDay = beginTime; String tz = null; if (allDay) { tz = TimeZone.getDefault().getID(); beginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, beginTime, tz); } // Handle multiple alerts for the same event ID. if (eventIds.containsKey(eventId)) { NotificationInfo oldInfo = eventIds.get(eventId); long oldBeginTimeAdjustedForAllDay = oldInfo.startMillis; if (allDay) { oldBeginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, oldInfo.startMillis, tz); } // Determine whether to replace the previous reminder with this one. // Query results are sorted so this one will always have a lower start time. long oldStartInterval = oldBeginTimeAdjustedForAllDay - currentTime; long newStartInterval = beginTimeAdjustedForAllDay - currentTime; boolean dropOld; if (newStartInterval < 0 && oldStartInterval > 0) { // Use this reminder if this event started recently dropOld = Math.abs(newStartInterval) < MIN_DEPRIORITIZE_GRACE_PERIOD_MS; } else { // ... or if this one has a closer start time. dropOld = Math.abs(newStartInterval) < Math.abs(oldStartInterval); } if (dropOld) { // This is a recurring event that has a more relevant start time, // drop other reminder in favor of this one. // // It will only be present in 1 of these buckets; just remove from // multiple buckets since this occurrence is rare enough that the // inefficiency of multiple removals shouldn't be a big deal to // justify a more complicated data structure. Expired events don't // have individual notifications so we don't need to clean that up. highPriorityEvents.remove(oldInfo); mediumPriorityEvents.remove(oldInfo); if (DEBUG) { Log.d(TAG, "Dropping alert for recurring event ID:" + oldInfo.eventId + ", startTime:" + oldInfo.startMillis + " in favor of startTime:" + newInfo.startMillis); } } else { // Skip duplicate reminders for the same event instance. continue; } } // TODO: Prioritize by "primary" calendar eventIds.put(eventId, newInfo); long highPriorityCutoff = currentTime - getGracePeriodMs(beginTime, endTime, allDay); if (beginTimeAdjustedForAllDay > highPriorityCutoff) { // High priority = future events or events that just started highPriorityEvents.add(newInfo); } else if (allDay && tz != null && DateUtils.isToday(beginTimeAdjustedForAllDay)) { // Medium priority = in progress all day events mediumPriorityEvents.add(newInfo); } else { lowPriorityEvents.add(newInfo); } } // TODO(cwren) add beginTime/startTime GlobalDismissManager.processEventIds(context, eventIds.keySet()); } finally { if (alertCursor != null) { alertCursor.close(); } } return numFired; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static String formatSameDayTime(final Context context, final long timestamp) { if (context == null) return null; if (DateUtils.isToday(timestamp)) return DateUtils.formatDateTime(context, timestamp, DateFormat.is24HourFormat(context) ? DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR); return DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_DATE); }