List of usage examples for android.text.format Time set
public void set(Time that)
From source file:com.android.calendar.AllInOneActivity.java
private void initFragments(long timeMillis, int viewType, Bundle icicle) { if (DEBUG) {//from w w w . jav a 2 s. c om Log.d(TAG, "Initializing to " + timeMillis + " for view " + viewType); } FragmentTransaction ft = getFragmentManager().beginTransaction(); if (mShowCalendarControls) { Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true); ft.replace(R.id.mini_month, miniMonthFrag); mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag); Fragment selectCalendarsFrag = new SelectVisibleCalendarsFragment(); ft.replace(R.id.calendar_list, selectCalendarsFrag); mController.registerEventHandler(R.id.calendar_list, (EventHandler) selectCalendarsFrag); } if (!mShowCalendarControls || viewType == ViewType.EDIT) { mMiniMonth.setVisibility(View.GONE); mCalendarsList.setVisibility(View.GONE); } EventInfo info = null; if (viewType == ViewType.EDIT) { mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW); long eventId = -1; Intent intent = getIntent(); Uri data = intent.getData(); if (data != null) { try { eventId = Long.parseLong(data.getLastPathSegment()); } catch (NumberFormatException e) { if (DEBUG) { Log.d(TAG, "Create new event"); } } } else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) { eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID); } long begin = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1); long end = intent.getLongExtra(EXTRA_EVENT_END_TIME, -1); info = new EventInfo(); if (end != -1) { info.endTime = new Time(); info.endTime.set(end); } if (begin != -1) { info.startTime = new Time(); info.startTime.set(begin); } info.id = eventId; // We set the viewtype so if the user presses back when they are // done editing the controller knows we were in the Edit Event // screen. Likewise for eventId mController.setViewType(viewType); mController.setEventId(eventId); } else { mPreviousView = viewType; } setMainPane(ft, R.id.main_pane, viewType, timeMillis, true); ft.commit(); // this needs to be after setMainPane() Time t = new Time(mTimeZone); t.set(timeMillis); if (viewType == ViewType.AGENDA && icicle != null) { mController.sendEvent(this, EventType.GO_TO, t, null, icicle.getLong(BUNDLE_KEY_EVENT_ID, -1), viewType); } else if (viewType != ViewType.EDIT) { mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType); } }
From source file:com.jogden.spunkycharts.traditionalchart.TraditionalChartFragmentAdapter.java
private void _populateQueues(final int cursorStartPos) { Thread thisThread = new Thread() { public void run() { /* can't bail(risk deadlocking on the count-down latch) */ _populateLck.lock();// w w w.j a v a 2 s . co m try { if (cursorStartPos > 0) /* back one because moveToNext() ) */ _myCursor.moveToPosition(cursorStartPos - 1); else _myCursor.moveToPosition(-1); int mergeNum = _chartFreq.value / DataClientInterface.TIME_GRANULARITY; /* reset _lastPutTime */ _lastPutTime = null; // DEBUG DataContentService.dumpDatabaseTableToLogCat(_symbol, _thisConsumer); /* start on a clean seg , i.e mod freq == 0 */ boolean cleanStart = true; Time time = new Time(); while (_myCursor.moveToNext()) { time.set(_myCursor.getLong(0)); if (time.minute % mergeNum == 0) break; cleanStart = false; } _myCursor.moveToPrevious(); OHLC[] prices = new OHLC[mergeNum]; int[] vols = new int[mergeNum]; time.set(0); int modCount = 0; // issue will null time if cursor is done here !! // we throw a *LogicError if its a problem later. while (_myCursor.moveToNext() && !this.isInterrupted()) { prices[modCount] = new OHLC(_myCursor.getFloat(1), _myCursor.getFloat(2), _myCursor.getFloat(3), _myCursor.getFloat(4)); vols[modCount] = _myCursor.getInt(5); if (modCount == 0) time.set(_myCursor.getLong(0)); if (modCount + 1 >= mergeNum) { OHLC mPrices = _mergePrices(prices); int mVols = _mergeVolumes(vols); //_timeStampQueue.put( time.format("%H:%M") ); /* time must come first since it may fill gaps in price/vol */ _putTime(time); _ohlcQueue.put(mPrices); _volumeQueue.put(mVols); modCount = 0;/* Log.d("Data-Consumer-Populate", mPrices.toString +" " + String.valueOf(mVols) + " " + time );*/ } else ++modCount; } /* don't forget about an unclean end */ if (modCount != 0) { // _timeStampQueue.put( time.format("%H:%M") ); /* time must come first since it may fill gaps in price/vol */ _putTime(time); _ohlcQueue.put(_mergePrices(Arrays.copyOf(prices, modCount))); _volumeQueue.put(_mergeVolumes(Arrays.copyOf(vols, modCount))); /* Log.d("Data-Consumer-Populate", _lastPriceSeg.toString() +" " + String.valueOf(_lastVolSeg) + " " + time );*/ } if (time.toMillis(true) == 0) throw new TraditionalChartLogicError("attempt to evaluate a null time in PopulateQueues; " + "its possible there were no granular segs after cleaning " + "the non-logically aligned front segs, and thus no valid time."); _lastSegTime.setToNow(); _lastSegTime.hour = time.hour; _lastSegTime.minute = time.minute; // _updateTime.setToNow(); _streamReady.set(true); /* unclean start needs extra counts to avoid deadlock */ for (int i = 0; !cleanStart && i < 2; ++i) _updateLtch.countDown(); } catch (InterruptedException e) { _clear(); } catch (RuntimeException e) { _clear(); throw e; } finally { _activeThreads.remove(this); _populateLck.unlock(); } } }; _activeThreads.add(thisThread); thisThread.start(); }
From source file:com.android.calendar.AllInOneActivity.java
@Override protected void onCreate(Bundle icicle) { if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) { setTheme(R.style.CalendarTheme_WithActionBarWallpaper); }//ww w .j a va 2s . c om super.onCreate(icicle); dynamicTheme.onCreate(this); if (icicle != null && icicle.containsKey(BUNDLE_KEY_CHECK_ACCOUNTS)) { mCheckForAccounts = icicle.getBoolean(BUNDLE_KEY_CHECK_ACCOUNTS); } // Launch add google account if this is first time and there are no // accounts yet if (mCheckForAccounts && !Utils.getSharedPreference(this, GeneralPreferences.KEY_SKIP_SETUP, false)) { mHandler = new QueryHandler(this.getContentResolver()); mHandler.startQuery(0, null, Calendars.CONTENT_URI, new String[] { Calendars._ID }, null, null /* selection args */, null /* sort order */); } // This needs to be created before setContentView mController = CalendarController.getInstance(this); // Check and ask for most needed permissions checkAppPermissions(); // Get time from intent or icicle long timeMillis = -1; int viewType = -1; final Intent intent = getIntent(); if (icicle != null) { timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME); viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1); } else { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { // Open EventInfo later timeMillis = parseViewAction(intent); } if (timeMillis == -1) { timeMillis = Utils.timeFromIntentInMillis(intent); } } if (viewType == -1 || viewType > ViewType.MAX_VALUE) { viewType = Utils.getViewTypeFromIntentAndSharedPref(this); } mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater); Time t = new Time(mTimeZone); t.set(timeMillis); if (DEBUG) { if (icicle != null && intent != null) { Log.d(TAG, "both, icicle:" + icicle.toString() + " intent:" + intent.toString()); } else { Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent); } } Resources res = getResources(); mHideString = res.getString(R.string.hide_controls); mShowString = res.getString(R.string.show_controls); mOrientation = res.getConfiguration().orientation; if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) { mControlsAnimateWidth = (int) res.getDimension(R.dimen.calendar_controls_width); if (mControlsParams == null) { mControlsParams = new LayoutParams(mControlsAnimateWidth, 0); } mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } else { // Make sure width is in between allowed min and max width values mControlsAnimateWidth = Math.max(res.getDisplayMetrics().widthPixels * 45 / 100, (int) res.getDimension(R.dimen.min_portrait_calendar_controls_width)); mControlsAnimateWidth = Math.min(mControlsAnimateWidth, (int) res.getDimension(R.dimen.max_portrait_calendar_controls_width)); } mControlsAnimateHeight = (int) res.getDimension(R.dimen.calendar_controls_height); mHideControls = !Utils.getSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, true); mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config); mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config); mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month); mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls); mShowEventDetailsWithAgenda = Utils.getConfigBool(this, R.bool.show_event_details_with_agenda); mShowEventInfoFullScreenAgenda = Utils.getConfigBool(this, R.bool.agenda_show_event_info_full_screen); mShowEventInfoFullScreen = Utils.getConfigBool(this, R.bool.show_event_info_full_screen); mCalendarControlsAnimationTime = res.getInteger(R.integer.calendar_controls_animation_time); Utils.setAllowWeekForDetailView(mIsMultipane); // setContentView must be called before configureActionBar setContentView(R.layout.all_in_one_material); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.navigation_view); mFab = (FloatingActionButton) findViewById(R.id.floating_action_button); if (mIsTabletConfig) { mDateRange = (TextView) findViewById(R.id.date_bar); mWeekTextView = (TextView) findViewById(R.id.week_num); } else { mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null); } setupToolbar(viewType); setupNavDrawer(); setupFloatingActionButton(); mHomeTime = (TextView) findViewById(R.id.home_time); mMiniMonth = findViewById(R.id.mini_month); if (mIsTabletConfig && mOrientation == Configuration.ORIENTATION_PORTRAIT) { mMiniMonth.setLayoutParams( new RelativeLayout.LayoutParams(mControlsAnimateWidth, mControlsAnimateHeight)); } mCalendarsList = findViewById(R.id.calendar_list); mMiniMonthContainer = findViewById(R.id.mini_month_container); mSecondaryPane = findViewById(R.id.secondary_pane); // Must register as the first activity because this activity can modify // the list of event handlers in it's handle method. This affects who // the rest of the handlers the controller dispatches to are. mController.registerFirstEventHandler(HANDLER_KEY, this); initFragments(timeMillis, viewType, icicle); // Listen for changes that would require this to be refreshed SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(this); mContentResolver = getContentResolver(); }
From source file:com.tdispatch.passenger.fragment.ControlCenterFragment.java
/**[ BookingConfirmationDialogClickListener ]**********************************************************************/ @Override/*from ww w .j av a 2 s. co m*/ public void bookingConfirmed(LocationData pickup, LocationData dropoff, Long pickupMillis) { int maxDaysAhead = getResources().getInteger(R.integer.caboffice_settings_new_bookings_max_days_ahead); Boolean result = false; Boolean pickupMillisInvalid = false; String pickupMillisBodyId = ""; if (pickupMillis != null) { Long diff = (pickupMillis - System.currentTimeMillis()); if (diff > 0) { if (diff > (WebnetTools.MILLIS_PER_MINUTE * 5)) { if (diff < (WebnetTools.MILLIS_PER_DAY * maxDaysAhead)) { // keep it } else { pickupMillisBodyId = getString(R.string.new_booking_pickup_date_too_ahead_body_fmt, maxDaysAhead); pickupMillisInvalid = true; } } else { pickupMillis = null; } } else { pickupMillisBodyId = getString(R.string.new_booking_pickup_date_already_passed); pickupMillisInvalid = true; } } if (pickupMillisInvalid == false) { if (mPickupAddress != null) { mCommonHostActivity.lockUI(); // prepare booking try { AccountData user = TDApplication.getSessionManager().getAccountData(); JSONObject json = new JSONObject(); JSONObject passenger = new JSONObject(); passenger.put("name", user.getFullName()); passenger.put("phone", (user.getPhone() != null) ? user.getPhone() : ""); passenger.put("email", (user.getEmail() != null) ? user.getEmail() : ""); json.put("passenger", passenger); // pickup location json.put("pickup_location", pickup.toJSON()); if (pickupMillis != null) { Time t = new Time(); t.set(pickupMillis); String timeStr = t.format3339(false).replace(".000+", "+"); // FIXME API BUG json.put("pickup_time", timeStr); } // dropoff if (mDropoffAddress != null) { json.put("dropoff_location", dropoff.toJSON()); } json.put("passengers", 1); json.put("status", "incoming"); WebnetTools.executeAsyncTask(new NewBookingAsyncTask(), json); result = true; } catch (Exception e) { e.printStackTrace(); } } else { showDialog(GenericDialogFragment.DIALOG_TYPE_ERROR, R.string.dialog_error_title, R.string.new_booking_no_pickup_location_body); } } else { showDialog(GenericDialogFragment.DIALOG_TYPE_ERROR, getString(R.string.dialog_error_title), pickupMillisBodyId); } if (result == false) { mCommonHostActivity.unlockUI(); } }
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 . jav a 2s . c o m */ 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.xandy.calendar.AllInOneActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { Time t = null; int viewType = ViewType.CURRENT; long extras = CalendarController.EXTRA_GOTO_TIME; final int itemId = item.getItemId(); if (itemId == R.id.action_refresh) { mController.refreshCalendars();//from ww w. ja va2 s .c om return true; } else if (itemId == R.id.action_today) { viewType = ViewType.CURRENT; t = new Time(mTimeZone); t.setToNow(); extras |= CalendarController.EXTRA_GOTO_TODAY; } else if (itemId == R.id.action_create_event) { t = new Time(); t.set(mController.getTime()); if (t.minute > 30) { t.hour++; t.minute = 0; } else if (t.minute > 0 && t.minute < 30) { t.minute = 30; } mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, t.toMillis(true), 0, 0, 0, -1); return true; } else if (itemId == R.id.action_select_visible_calendars) { mController.sendEvent(this, EventType.LAUNCH_SELECT_VISIBLE_CALENDARS, null, null, 0, 0); return true; } else if (itemId == R.id.action_settings) { mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, 0, 0); return true; } else if (itemId == R.id.action_hide_controls) { mHideControls = !mHideControls; Utils.setSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, !mHideControls); item.setTitle(mHideControls ? mShowString : mHideString); if (!mHideControls) { mMiniMonth.setVisibility(View.VISIBLE); mCalendarsList.setVisibility(View.VISIBLE); mMiniMonthContainer.setVisibility(View.VISIBLE); } final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this, "controlsOffset", mHideControls ? 0 : mControlsAnimateWidth, mHideControls ? mControlsAnimateWidth : 0); slideAnimation.setDuration(mCalendarControlsAnimationTime); ObjectAnimator.setFrameDelay(0); slideAnimation.start(); return true; } else if (itemId == R.id.action_search) { return false; } else { return mExtensions.handleItemSelected(item, this); } mController.sendEvent(this, EventType.GO_TO, t, null, t, -1, viewType, extras, null, null); return true; }
From source file:com.android.calendar.AllInOneActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { Time t = null; int viewType = ViewType.CURRENT; long extras = CalendarController.EXTRA_GOTO_TIME; final int itemId = item.getItemId(); if (itemId == R.id.action_refresh) { mController.refreshCalendars();//from w w w.j a va2 s .c o m return true; } else if (itemId == R.id.action_today) { viewType = ViewType.CURRENT; t = new Time(mTimeZone); t.setToNow(); extras |= CalendarController.EXTRA_GOTO_TODAY; } else if (itemId == R.id.action_goto) { Time todayTime; t = new Time(mTimeZone); t.set(mController.getTime()); todayTime = new Time(mTimeZone); todayTime.setToNow(); if (todayTime.month == t.month) { t = todayTime; } DatePickerDialog datePickerDialog = DatePickerDialog .newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) { Time selectedTime = new Time(mTimeZone); selectedTime.year = year; selectedTime.month = monthOfYear; selectedTime.monthDay = dayOfMonth; long extras = CalendarController.EXTRA_GOTO_TIME | CalendarController.EXTRA_GOTO_DATE; mController.sendEvent(this, EventType.GO_TO, selectedTime, null, selectedTime, -1, ViewType.CURRENT, extras, null, null); } }, t.year, t.month, t.monthDay); datePickerDialog.show(getFragmentManager(), "datePickerDialog"); } else if (itemId == R.id.action_hide_controls) { mHideControls = !mHideControls; Utils.setSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, !mHideControls); item.setTitle(mHideControls ? mShowString : mHideString); if (!mHideControls) { mMiniMonth.setVisibility(View.VISIBLE); mCalendarsList.setVisibility(View.VISIBLE); mMiniMonthContainer.setVisibility(View.VISIBLE); } final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this, "controlsOffset", mHideControls ? 0 : mControlsAnimateWidth, mHideControls ? mControlsAnimateWidth : 0); slideAnimation.setDuration(mCalendarControlsAnimationTime); ObjectAnimator.setFrameDelay(0); slideAnimation.start(); return true; } else if (itemId == R.id.action_search) { return false; } else if (itemId == R.id.action_import) { ImportActivity.pickImportFile(this); } else { return mExtensions.handleItemSelected(item, this); } mController.sendEvent(this, EventType.GO_TO, t, null, t, -1, viewType, extras, null, null); return true; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static String formatToLongTimeString(final Context context, final long timestamp) { if (context == null) return null; final Time then = new Time(); then.set(timestamp); final Time now = new Time(); now.setToNow();// w w w . j ava 2 s.co m int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_CAP_AMPM; format_flags |= DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME; return DateUtils.formatDateTime(context, timestamp, format_flags); }
From source file:com.dwdesign.tweetings.util.Utils.java
public static String formatTimeStampString(final Context context, final long timestamp) { if (context == null) return null; final Time then = new Time(); then.set(timestamp); final Time now = new Time(); now.setToNow();// w ww.j a va 2 s. c o m int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_AMPM; if (then.year != now.year) { format_flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE; } else if (then.yearDay != now.yearDay) { format_flags |= DateUtils.FORMAT_SHOW_DATE; } else { format_flags |= DateUtils.FORMAT_SHOW_TIME; } return DateUtils.formatDateTime(context, timestamp, format_flags); }
From source file:com.android.mms.ui.MessageUtils.java
public static String getTimeDividerString(Context context, long when) { Time then = new Time(); then.set(when); Time now = new Time(); now.setToNow();/*from www. j av a2 s . com*/ // Basic settings for formatDateTime() we want for all cases. int formatFlags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_AMPM; // If the message is from a different year, show the date and year. if (then.year != now.year) { formatFlags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE; } else if (then.yearDay != now.yearDay) { // If it is from a different day than today, show only the date. formatFlags |= DateUtils.FORMAT_SHOW_DATE; Date curDate = new Date(); Date cur = new Date(curDate.getYear(), curDate.getMonth(), curDate.getDate(), 0, 0, 0); long oneDay = 24 * 60 * 60 * 1000; long elapsedTime = cur.getTime() - when; if (elapsedTime < oneDay && elapsedTime > 0) { return context.getResources().getString(R.string.str_ipmsg_yesterday); } } else { return context.getString(R.string.str_ipmsg_today); } return DateUtils.formatDateTime(context, when, formatFlags); }