public static String prettyTimestamp(Timestamp t, boolean isChat) { // Set time in UTC time Time time = new Time("UTC"); Calendar cal = Calendar.getInstance(); cal.setTime(t); time.set( cal.get(Calendar.SECOND), cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)); // Switch to device timezone time.switchTimezone(Time.getCurrentTimezone()); Time startOfDay = new Time(Time.getCurrentTimezone()); startOfDay.setToNow(); startOfDay.hour = 0; startOfDay.minute = 0; startOfDay.second = 0; Time startOfYear = new Time(Time.getCurrentTimezone()); startOfYear.setToNow(); startOfYear.hour = 0; startOfYear.minute = 0; startOfYear.second = 0; startOfYear.monthDay = 0; startOfYear.month = 0; Time startOfTime = new Time(Time.getCurrentTimezone()); startOfTime.set(0); if (t.equals(new Timestamp(0, 0, 0, 0, 0, 0, 0))) { return ""; } else if (isChat) { if (time.after(startOfDay)) { return time.format("%H:%M"); } else if (time.after(startOfYear)) { return time.format("%b %d, %H:%M"); } else { return time.format("%b %d %Y, %H:%M"); } } else { if (time.after(startOfDay)) { return time.format("%H:%M"); } else if (time.after(startOfYear)) { return time.format("%b %d"); } else { return time.format("%b %d %Y"); } } }
private String getMonthAndYearString() { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY; mStringBuilder.setLength(0); long millis = mCalendar.getTimeInMillis(); return DateUtils.formatDateRange( getContext(), mFormatter, millis, millis, flags, Time.getCurrentTimezone()) .toString(); }
public static Time timeFrom3339(String s3339) { final android.text.format.Time time = new Time(); if (TextUtils.isEmpty(s3339)) { return time; } try { time.parse3339(s3339); } catch (TimeFormatException e) { return time; } time.switchTimezone(android.text.format.Time.getCurrentTimezone()); return time; }
/** * Sets all the parameters for displaying this week. The only required parameter is the week * number. Other parameters have a default value and will only update if a new value is included, * except for focus month, which will always default to no focus month if no value is passed in. * See {@link #VIEW_PARAMS_HEIGHT} for more info on parameters. * * @param params A map of the new parameters, see {@link #VIEW_PARAMS_HEIGHT} */ public void setMonthParams(HashMap<String, Integer> params) { if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) { throw new InvalidParameterException("You must specify month and year for this view"); } setTag(params); // We keep the current value for any params not present if (params.containsKey(VIEW_PARAMS_HEIGHT)) { mRowHeight = params.get(VIEW_PARAMS_HEIGHT); if (mRowHeight < MIN_HEIGHT) { mRowHeight = MIN_HEIGHT; } } if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) { mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY); } // Allocate space for caching the day numbers and focus values mMonth = params.get(VIEW_PARAMS_MONTH); mYear = params.get(VIEW_PARAMS_YEAR); // Figure out what day today is final Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); mHasToday = false; mToday = -1; mCalendar.set(Calendar.MONTH, mMonth); mCalendar.set(Calendar.YEAR, mYear); mCalendar.set(Calendar.DAY_OF_MONTH, 1); mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK); if (params.containsKey(VIEW_PARAMS_WEEK_START)) { mWeekStart = params.get(VIEW_PARAMS_WEEK_START); } else { mWeekStart = mCalendar.getFirstDayOfWeek(); } mNumCells = Utils.getDaysInMonth(mMonth, mYear); for (int i = 0; i < mNumCells; i++) { final int day = i + 1; if (sameDay(day, today)) { mHasToday = true; mToday = day; } } mNumRows = calculateNumRows(); // Invalidate cached accessibility information. mTouchHelper.invalidateRoot(); }
private boolean initialiseSunMoon() { boolean isDay = false; sunOffset = mViewHeight; moonOffset = 0; // 6am till 6pm is considered day time; Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); if (today.hour >= 6 || today.hour < 18) { isDay = true; sunOffset = 0; moonOffset = -mViewHeight; } return isDay; }
public void deleteOldAlerts() { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences((Context) this); int maxAge = sharedPrefs.getInt("max_age", AlertsContract.DEFAULT_MAX_AGE); long maxAgeSeconds = maxAge * 24 * 60 * 60 * 1000; Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); long olderThan = today.toMillis(true) - maxAgeSeconds; String selection = AlertsContract.RECEIVED_AT + " < ?"; String[] selectionArgs = {String.valueOf(olderThan)}; getContentResolver().delete(AlertsContract.CONTENT_URI_ALERTS, selection, selectionArgs); }
public void setMonthParams(HashMap<String, Integer> params) { if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) { throw new InvalidParameterException("You must specify month and year for this view"); } setTag(params); if (params.containsKey(VIEW_PARAMS_HEIGHT)) { mRowHeight = params.get(VIEW_PARAMS_HEIGHT); if (mRowHeight < MIN_HEIGHT) { mRowHeight = MIN_HEIGHT; } } if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) { mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY); } mMonth = params.get(VIEW_PARAMS_MONTH); mYear = params.get(VIEW_PARAMS_YEAR); final Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); mHasToday = false; mToday = -1; mCalendar.set(Calendar.MONTH, mMonth); mCalendar.set(Calendar.YEAR, mYear); mCalendar.set(Calendar.DAY_OF_MONTH, 1); mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK); if (params.containsKey(VIEW_PARAMS_WEEK_START)) { mWeekStart = params.get(VIEW_PARAMS_WEEK_START); } else { mWeekStart = mCalendar.getFirstDayOfWeek(); } mNumCells = Utils.getDaysInMonth(mMonth, mYear); for (int i = 0; i < mNumCells; i++) { final int day = i + 1; if (sameDay(day, today)) { mHasToday = true; mToday = day; } } mNumRows = calculateNumRows(); }
/** * Queries for all the reminders of the events in the instancesCursor, and schedules the alarm for * the next upcoming reminder. */ private static void queryNextReminderAndSchedule( Cursor instancesCursor, Context context, ContentResolver contentResolver, AlarmManagerInterface alarmManager, int batchSize, long currentMillis) { if (AlertService.DEBUG) { int eventCount = instancesCursor.getCount(); if (eventCount == 0) { Log.d(TAG, "No events found starting within 1 week."); } else { Log.d(TAG, "Query result count for events starting within 1 week: " + eventCount); } } // Put query results of all events starting within some interval into map of event ID to // local start time. Map<Integer, List<Long>> eventMap = new HashMap<Integer, List<Long>>(); Time timeObj = new Time(); long nextAlarmTime = Long.MAX_VALUE; int nextAlarmEventId = 0; instancesCursor.moveToPosition(-1); while (!instancesCursor.isAfterLast()) { int index = 0; eventMap.clear(); StringBuilder eventIdsForQuery = new StringBuilder(); eventIdsForQuery.append('('); while (index++ < batchSize && instancesCursor.moveToNext()) { int eventId = instancesCursor.getInt(INSTANCES_INDEX_EVENTID); long begin = instancesCursor.getLong(INSTANCES_INDEX_BEGIN); boolean allday = instancesCursor.getInt(INSTANCES_INDEX_ALL_DAY) != 0; long localStartTime; if (allday) { // Adjust allday to local time. localStartTime = Utils.convertAlldayUtcToLocal(timeObj, begin, Time.getCurrentTimezone()); } else { localStartTime = begin; } List<Long> startTimes = eventMap.get(eventId); if (startTimes == null) { startTimes = new ArrayList<Long>(); eventMap.put(eventId, startTimes); eventIdsForQuery.append(eventId); eventIdsForQuery.append(","); } startTimes.add(localStartTime); // Log for debugging. if (Log.isLoggable(TAG, Log.DEBUG)) { timeObj.set(localStartTime); StringBuilder msg = new StringBuilder(); msg.append("Events cursor result -- eventId:").append(eventId); msg.append(", allDay:").append(allday); msg.append(", start:").append(localStartTime); msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")"); Log.d(TAG, msg.toString()); } } if (eventIdsForQuery.charAt(eventIdsForQuery.length() - 1) == ',') { eventIdsForQuery.deleteCharAt(eventIdsForQuery.length() - 1); } eventIdsForQuery.append(')'); // Query the reminders table for the events found. Cursor cursor = null; try { cursor = contentResolver.query( Reminders.CONTENT_URI, REMINDERS_PROJECTION, REMINDERS_WHERE + eventIdsForQuery, null, null); // Process the reminders query results to find the next reminder time. cursor.moveToPosition(-1); while (cursor.moveToNext()) { int eventId = cursor.getInt(REMINDERS_INDEX_EVENT_ID); int reminderMinutes = cursor.getInt(REMINDERS_INDEX_MINUTES); List<Long> startTimes = eventMap.get(eventId); if (startTimes != null) { for (Long startTime : startTimes) { long alarmTime = startTime - reminderMinutes * DateUtils.MINUTE_IN_MILLIS; if (alarmTime > currentMillis && alarmTime < nextAlarmTime) { nextAlarmTime = alarmTime; nextAlarmEventId = eventId; } if (Log.isLoggable(TAG, Log.DEBUG)) { timeObj.set(alarmTime); StringBuilder msg = new StringBuilder(); msg.append("Reminders cursor result -- eventId:").append(eventId); msg.append(", startTime:").append(startTime); msg.append(", minutes:").append(reminderMinutes); msg.append(", alarmTime:").append(alarmTime); msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")"); Log.d(TAG, msg.toString()); } } } } } finally { if (cursor != null) { cursor.close(); } } } // Schedule the alarm for the next reminder time. if (nextAlarmTime < Long.MAX_VALUE) { scheduleAlarm(context, nextAlarmEventId, nextAlarmTime, currentMillis, alarmManager); } }
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); final Activity activity = getActivity(); // Make sure to always use the same preferences file regardless of the package name // we're running under final PreferenceManager preferenceManager = getPreferenceManager(); final SharedPreferences sharedPreferences = getSharedPreferences(activity); preferenceManager.setSharedPreferencesName(SHARED_PREFS_NAME); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.general_preferences); final PreferenceScreen preferenceScreen = getPreferenceScreen(); mAlert = (CheckBoxPreference) preferenceScreen.findPreference(KEY_ALERTS); mVibrate = (CheckBoxPreference) preferenceScreen.findPreference(KEY_ALERTS_VIBRATE); Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); if (vibrator == null || !vibrator.hasVibrator()) { PreferenceCategory mAlertGroup = (PreferenceCategory) preferenceScreen.findPreference(KEY_ALERTS_CATEGORY); mAlertGroup.removePreference(mVibrate); } mRingtone = (RingtonePreference) preferenceScreen.findPreference(KEY_ALERTS_RINGTONE); String ringToneUri = Utils.getRingTonePreference(activity); // Set the ringToneUri to the backup-able shared pref only so that // the Ringtone dialog will open up with the correct value. final Editor editor = preferenceScreen.getEditor(); editor.putString(GeneralPreferences.KEY_ALERTS_RINGTONE, ringToneUri).apply(); String ringtoneDisplayString = getRingtoneTitleFromUri(activity, ringToneUri); mRingtone.setSummary(ringtoneDisplayString == null ? "" : ringtoneDisplayString); mPopup = (CheckBoxPreference) preferenceScreen.findPreference(KEY_ALERTS_POPUP); mUseHomeTZ = (CheckBoxPreference) preferenceScreen.findPreference(KEY_HOME_TZ_ENABLED); mHideDeclined = (CheckBoxPreference) preferenceScreen.findPreference(KEY_HIDE_DECLINED); mWeekStart = (ListPreference) preferenceScreen.findPreference(KEY_WEEK_START_DAY); mDefaultReminder = (ListPreference) preferenceScreen.findPreference(KEY_DEFAULT_REMINDER); mHomeTZ = preferenceScreen.findPreference(KEY_HOME_TZ); mSnoozeDelay = (ListPreference) preferenceScreen.findPreference(KEY_DEFAULT_SNOOZE_DELAY); buildSnoozeDelayEntries(); mDefaultStart = (ListPreference) preferenceScreen.findPreference(KEY_DEFAULT_START); mDefaultStart.setOnPreferenceChangeListener(this); mWeekStart.setSummary(mWeekStart.getEntry()); mDefaultReminder.setSummary(mDefaultReminder.getEntry()); mSnoozeDelay.setSummary(mSnoozeDelay.getEntry()); mDefaultStart.setSummary(mDefaultStart.getEntry()); // This triggers an asynchronous call to the provider to refresh the data in shared pref mTimeZoneId = Utils.getTimeZone(activity, null); SharedPreferences prefs = CalendarUtils.getSharedPreferences(activity, Utils.SHARED_PREFS_NAME); // Utils.getTimeZone will return the currentTimeZone instead of the one // in the shared_pref if home time zone is disabled. So if home tz is // off, we will explicitly read it. if (!prefs.getBoolean(KEY_HOME_TZ_ENABLED, false)) { mTimeZoneId = prefs.getString(KEY_HOME_TZ, Time.getCurrentTimezone()); } mHomeTZ.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showTimezoneDialog(); return true; } }); if (mTzPickerUtils == null) { mTzPickerUtils = new TimeZonePickerUtils(getActivity()); } CharSequence timezoneName = mTzPickerUtils.getGmtDisplayName( getActivity(), mTimeZoneId, System.currentTimeMillis(), false); mHomeTZ.setSummary(timezoneName != null ? timezoneName : mTimeZoneId); TimeZonePickerDialog tzpd = (TimeZonePickerDialog) activity.getFragmentManager().findFragmentByTag(FRAG_TAG_TIME_ZONE_PICKER); if (tzpd != null) { tzpd.setOnTimeZoneSetListener(this); } migrateOldPreferences(sharedPreferences); updateChildPreferences(); }
public boolean ftpDownload() { boolean status = false; final String username = "******"; final String password = "******"; final String hostname = "ftp.memelab.ca"; final int port = 21; String SFTPWORKINGDIR = "/public_html/jessescott/storage/android"; FTPClient ftp = new FTPClient(); try { ftp.connect(hostname, port); ftp.login(username, password); ftp.changeWorkingDirectory(SFTPWORKINGDIR); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(1024); ftp.enterLocalPassiveMode(); OutputStream output = null; FTPFile[] files = ftp.listFiles(); // Set Log Directory & File File logFile = new File(LOG_DIRECTORY + "logfile.txt"); Log.d("FTP", "LOG should exist at " + logFile.getAbsolutePath()); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } for (FTPFile f : files) { // Log Names Log.d("FTP", f.toFormattedString()); // Set Path String remoteFile = f.getName(); Log.d("FTP", "REMOTE file " + remoteFile); String localFile = MEDIA_DIRECTORY; localFile += remoteFile; Log.d("FTP", " is being put in LOCAL path " + localFile); output = new BufferedOutputStream(new FileOutputStream(localFile)); // Set Time Time now = new Time(Time.getCurrentTimezone()); now.setToNow(); // Set Logger BufferedWriter logger = new BufferedWriter(new FileWriter(logFile, true)); logger.append("Download for " + localFile + " started at " + now.format("%k:%M:%S")); logger.newLine(); Long startTime = System.currentTimeMillis(); // HTTP System.setProperty("http.keepAlive", "false"); // Get Files Boolean success = ftp.retrieveFile(remoteFile, output); status = success; if (success) { Log.d("FTP", "SUCCESS"); now.setToNow(); Long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; logger.append("Download for " + localFile + " finished at " + now.format("%k:%M:%S")); logger.newLine(); logger.append("for an elapsedTime of " + elapsedTime + " seconds"); logger.newLine(); logger.newLine(); } // Close Logger logger.flush(); logger.close(); // Close Buffer if (ftp != null) { output.close(); } } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } return status; }