Example usage for android.text.format Time set

List of usage examples for android.text.format Time set

Introduction

In this page you can find the example usage for android.text.format Time set.

Prototype

public void set(Time that) 

Source Link

Document

Copy the value of that to this Time object.

Usage

From source file:Main.java

public static boolean isYesterday(long when) {
    android.text.format.Time time = new android.text.format.Time();
    time.set(when);

    int thenYear = time.year;
    int thenMonth = time.month;
    int thenMonthDay = time.monthDay;

    time.set(System.currentTimeMillis());
    return (thenYear == time.year) && (thenMonth == time.month) && (time.monthDay - thenMonthDay == 1);
}

From source file:Main.java

@SuppressWarnings("deprecation")
public static String formatTimeStampString(Context context, long when, boolean fullFormat) {
    Time then = new Time();
    then.set(when);

    Time now = new Time();
    now.setToNow();/*www .  j a  v  a2 s  .  c o m*/

    // Basic settings for formatDateTime() we want for all cases.
    int format_flags = 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) {
        format_flags |= 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.
        format_flags |= DateUtils.FORMAT_SHOW_DATE;
    } else {
        // Otherwise, if the message is from today, show the time.
        format_flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    // If the caller has asked for full details, make sure to show the date
    // and time no matter what we've determined above (but still make
    // showing
    // the year only happen if it is a different year from today).
    if (fullFormat) {
        format_flags |= (DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
    }

    return DateUtils.formatDateTime(context, when, format_flags);
}

From source file:Main.java

/**
 * Get formatted time.//  w  w w . j av a 2s. co m
 *
 * @param publishedTime The published time in millis.
 *
 * @return The formatted time.
 */
static public String getFormattedTime(long publishedTime) {
    // This is copied from RecentCallsListActivity.java

    long now = System.currentTimeMillis();

    // Set the date/time field by mixing relative and absolute times.
    int flags = DateUtils.FORMAT_ABBREV_ALL;

    if (!DateUtils.isToday(publishedTime)) {
        // DateUtils.getRelativeTimeSpanString doesn't consider the nature
        // days comparing with DateUtils.getRelativeDayString. Override the
        // real date to implement the requirement.

        Time time = new Time();
        time.set(now);
        long gmtOff = time.gmtoff;
        int days = Time.getJulianDay(publishedTime, gmtOff) - Time.getJulianDay(now, gmtOff);

        // Set the delta from now to get the correct display
        publishedTime = now + days * DateUtils.DAY_IN_MILLIS;
    } else if (publishedTime > now && (publishedTime - now) < DateUtils.HOUR_IN_MILLIS) {
        // Avoid e.g. "1 minute left" when publish time is "07:00" and
        // current time is "06:58"
        publishedTime += DateUtils.MINUTE_IN_MILLIS;
    }

    return (DateUtils.getRelativeTimeSpanString(publishedTime, now, DateUtils.MINUTE_IN_MILLIS, flags))
            .toString();
}

From source file:com.joeyturczak.jtscanner.utils.Utility.java

public static long normalizeDate(long startDate) {
    // normalize the start date to the beginning of the (UTC) day
    Time time = new Time();
    time.set(startDate);
    int julianDay = Time.getJulianDay(startDate, time.gmtoff);
    return time.setJulianDay(julianDay);
}

From source file:com.socialdisasters.other.MessageAdapter.java

public static String formatTimeStampString(Context context, long when, boolean fullFormat) {
    Time then = new Time();
    then.set(when);
    Time now = new Time();
    now.setToNow();/*from  w  w w . j a  v  a  2 s . c om*/

    // Basic settings for formatDateTime() we want for all cases.
    int format_flags = DateUtils.FORMAT_ABBREV_ALL;

    // If the message is from a different year, show the date and year.
    if (then.year != now.year) {
        format_flags |= 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.
        format_flags |= DateUtils.FORMAT_SHOW_DATE;
    } else {
        // Otherwise, if the message is from today, show the time.
        format_flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    // If the caller has asked for full details, make sure to show the date
    // and time no matter what we've determined above (but still make showing
    // the year only happen if it is a different year from today).
    if (fullFormat) {
        format_flags |= (DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
    }

    return DateUtils.formatDateTime(context, when, format_flags);
}

From source file:com.android.calendar.alerts.AlarmScheduler.java

/**
 * Schedules an alarm for the EVENT_REMINDER_APP broadcast, for the specified
 * alarm time with a slight delay (to account for the possible duplicate broadcast
 * from the provider).//from   w ww  .ja v  a 2 s.  c o m
 */
private static void scheduleAlarm(Context context, long eventId, long alarmTime, long currentMillis,
        AlarmManagerInterface alarmManager) {
    // Max out the alarm time to 1 day out, so an alert for an event far in the future
    // (not present in our event query results for a limited range) can only be at
    // most 1 day late.
    long maxAlarmTime = currentMillis + MAX_ALARM_ELAPSED_MS;
    if (alarmTime > maxAlarmTime) {
        alarmTime = maxAlarmTime;
    }

    // Add a slight delay (see comments on the member var).
    alarmTime += ALARM_DELAY_MS;

    if (AlertService.DEBUG) {
        Time time = new Time();
        time.set(alarmTime);
        String schedTime = time.format("%a, %b %d, %Y %I:%M%P");
        Log.d(TAG, "Scheduling alarm for EVENT_REMINDER_APP broadcast for event " + eventId + " at " + alarmTime
                + " (" + schedTime + ")");
    }

    // Schedule an EVENT_REMINDER_APP broadcast with AlarmManager.  The extra is
    // only used by AlertService for logging.  It is ignored by Intent.filterEquals,
    // so this scheduling will still overwrite the alarm that was previously pending.
    // Note that the 'setClass' is required, because otherwise it seems the broadcast
    // can be eaten by other apps and we somehow may never receive it.
    Intent intent = new Intent(AlertReceiver.EVENT_REMINDER_APP_ACTION);
    intent.setClass(context, AlertReceiver.class);
    intent.putExtra(CalendarContract.CalendarAlerts.ALARM_TIME, alarmTime);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:com.granita.tasks.notification.NotificationActionUtils.java

private static Time makeTime(long timestamp, boolean allday) {
    Time result = new Time(allday ? Time.TIMEZONE_UTC : TimeZone.getDefault().getID());
    result.set(timestamp);
    result.allDay = allday;//from   ww  w  .ja  va2s.  c o  m
    return result;
}

From source file:com.android.deskclock.Utils.java

public static void setMidnightUpdater(Handler handler, Runnable runnable) {
    String timezone = TimeZone.getDefault().getID();
    if (handler == null || runnable == null || timezone == null) {
        return;//from   w  w  w  .  j a  v  a  2s  .  c o  m
    }
    long now = System.currentTimeMillis();
    Time time = new Time(timezone);
    time.set(now);
    long runInMillis = ((24 - time.hour) * 3600 - time.minute * 60 - time.second + 1) * 1000;
    handler.removeCallbacks(runnable);
    handler.postDelayed(runnable, runInMillis);
}

From source file:com.android.calendar.alerts.AlertService.java

public static boolean generateAlerts(Context context, NotificationMgr nm, AlarmManagerInterface alarmMgr,
        SharedPreferences prefs, Cursor alertCursor, final long currentTime, final int maxNotifications) {
    if (DEBUG) {/*from w ww  . ja  v a  2 s . c o m*/
        Log.d(TAG, "alertCursor count:" + alertCursor.getCount());
    }

    // Process the query results and bucketize events.
    ArrayList<NotificationInfo> highPriorityEvents = new ArrayList<NotificationInfo>();
    ArrayList<NotificationInfo> mediumPriorityEvents = new ArrayList<NotificationInfo>();
    ArrayList<NotificationInfo> lowPriorityEvents = new ArrayList<NotificationInfo>();
    int numFired = processQuery(alertCursor, context, currentTime, highPriorityEvents, mediumPriorityEvents,
            lowPriorityEvents);

    if (highPriorityEvents.size() + mediumPriorityEvents.size() + lowPriorityEvents.size() == 0) {
        nm.cancelAll();
        return true;
    }

    long nextRefreshTime = Long.MAX_VALUE;
    int currentNotificationId = 1;
    NotificationPrefs notificationPrefs = new NotificationPrefs(context, prefs, (numFired == 0));

    // If there are more high/medium priority events than we can show, bump some to
    // the low priority digest.
    redistributeBuckets(highPriorityEvents, mediumPriorityEvents, lowPriorityEvents, maxNotifications);

    // Post the individual higher priority events (future and recently started
    // concurrent events).  Order these so that earlier start times appear higher in
    // the notification list.
    for (int i = 0; i < highPriorityEvents.size(); i++) {
        NotificationInfo info = highPriorityEvents.get(i);
        String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis, info.allDay,
                info.location);
        postNotification(info, summaryText, context, true, notificationPrefs, nm, currentNotificationId++);

        // Keep concurrent events high priority (to appear higher in the notification list)
        // until 15 minutes into the event.
        nextRefreshTime = Math.min(nextRefreshTime, getNextRefreshTime(info, currentTime));
    }

    // Post the medium priority events (concurrent events that started a while ago).
    // Order these so more recent start times appear higher in the notification list.
    //
    // TODO: Post these with the same notification priority level as the higher priority
    // events, so that all notifications will be co-located together.
    for (int i = mediumPriorityEvents.size() - 1; i >= 0; i--) {
        NotificationInfo info = mediumPriorityEvents.get(i);
        // TODO: Change to a relative time description like: "Started 40 minutes ago".
        // This requires constant refreshing to the message as time goes.
        String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis, info.allDay,
                info.location);
        postNotification(info, summaryText, context, false, notificationPrefs, nm, currentNotificationId++);

        // Refresh when concurrent event ends so it will drop into the expired digest.
        nextRefreshTime = Math.min(nextRefreshTime, getNextRefreshTime(info, currentTime));
    }

    // Post the low priority events as 1 combined notification.
    int numLowPriority = lowPriorityEvents.size();
    if (numLowPriority > 0) {
        String expiredDigestTitle = getDigestTitle(lowPriorityEvents);
        NotificationWrapper notification;
        if (numLowPriority == 1) {
            // If only 1 expired event, display an "old-style" basic alert.
            NotificationInfo info = lowPriorityEvents.get(0);
            String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis, info.allDay,
                    info.location);
            notification = AlertReceiver.makeBasicNotification(context, info.eventName, summaryText,
                    info.startMillis, info.endMillis, info.eventId, AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                    false, Notification.PRIORITY_MIN);
        } else {
            // Multiple expired events are listed in a digest.
            notification = AlertReceiver.makeDigestNotification(context, lowPriorityEvents, expiredDigestTitle,
                    false);
        }

        // Add options for a quiet update.
        addNotificationOptions(notification, true, expiredDigestTitle, notificationPrefs.getDefaultVibrate(),
                notificationPrefs.getRingtoneAndSilence(),
                false); /* Do not show the LED for the expired events. */

        if (DEBUG) {
            Log.d(TAG, "Quietly posting digest alarm notification, numEvents:" + numLowPriority
                    + ", notificationId:" + AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
        }

        // Post the new notification for the group.
        nm.notify(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, notification);
    } else {
        nm.cancel(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
        if (DEBUG) {
            Log.d(TAG, "No low priority events, canceling the digest notification.");
        }
    }

    // Remove the notifications that are hanging around from the previous refresh.
    if (currentNotificationId <= maxNotifications) {
        nm.cancelAllBetween(currentNotificationId, maxNotifications);
        if (DEBUG) {
            Log.d(TAG, "Canceling leftover notification IDs " + currentNotificationId + "-" + maxNotifications);
        }
    }

    // Schedule the next silent refresh time so notifications will change
    // buckets (eg. drop into expired digest, etc).
    if (nextRefreshTime < Long.MAX_VALUE && nextRefreshTime > currentTime) {
        AlertUtils.scheduleNextNotificationRefresh(context, alarmMgr, nextRefreshTime);
        if (DEBUG) {
            long minutesBeforeRefresh = (nextRefreshTime - currentTime) / MINUTE_MS;
            Time time = new Time();
            time.set(nextRefreshTime);
            String msg = String.format("Scheduling next notification refresh in %d min at: " + "%d:%02d",
                    minutesBeforeRefresh, time.hour, time.minute);
            Log.d(TAG, msg);
        }
    } else if (nextRefreshTime < currentTime) {
        Log.e(TAG, "Illegal state: next notification refresh time found to be in the past.");
    }

    // Flushes old fired alerts from internal storage, if needed.
    AlertUtils.flushOldAlertsFromInternalStorage(context);

    return true;
}

From source file:net.xisberto.work_schedule.alarm.CountdownService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        if (ACTION_START.equals(intent.getAction())) {
            if (intent.hasExtra(AlarmMessageActivity.EXTRA_PERIOD_ID)) {
                int period_id = intent.getIntExtra(AlarmMessageActivity.EXTRA_PERIOD_ID,
                        R.string.fstp_entrance);
                period = Period.getPeriod(this, period_id);
            } else {
                stopSelf();//  w  w  w .ja v a  2 s  .com
                return super.onStartCommand(intent, flags, startId);
            }

            long millisInFuture = period.time.getTimeInMillis() - System.currentTimeMillis();
            if (millisInFuture > 0) {

                Intent mainIntent = new Intent(this, MainActivity.class);
                mainIntent.setAction(MainActivity.ACTION_SET_PERIOD);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Intent deleteIntent = new Intent(this, CountdownService.class);
                deleteIntent.setAction(ACTION_STOP);

                builder = new Builder(this).setSmallIcon(R.drawable.ic_stat_notification)
                        .setContentTitle(getString(period.getLabelId()))
                        .setTicker(getString(period.getLabelId())).setOnlyAlertOnce(true)
                        .setPriority(NotificationCompat.PRIORITY_LOW).setAutoCancel(false)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentIntent(PendingIntent.getActivity(this, period.getId(), mainIntent,
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setDeleteIntent(PendingIntent.getService(this, period.getId(), deleteIntent,
                                PendingIntent.FLAG_CANCEL_CURRENT));
                manager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
                manager.notify(0, builder.build());

                timer = new CountDownTimer(millisInFuture, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        Time t = new Time();
                        t.set(millisUntilFinished);
                        builder.setContentText(getString(R.string.time_until_alarm, t.format("%M:%S")));
                        manager.notify(0, builder.build());
                    }

                    @Override
                    public void onFinish() {
                        manager.cancel(0);
                        stopSelf();
                    }
                };

                timer.start();
            }
        } else if (ACTION_STOP_SPECIFIC.equals(intent.getAction())) {
            if (intent.hasExtra(AlarmMessageActivity.EXTRA_PERIOD_ID)) {
                int period_id = intent.getIntExtra(AlarmMessageActivity.EXTRA_PERIOD_ID,
                        R.string.fstp_entrance);
                if (period != null && period.getId() == period_id) {
                    stopAndCancel();
                }
            } else {
                stopSelf();
                return super.onStartCommand(intent, flags, startId);
            }
        } else if (ACTION_STOP.equals(intent.getAction())) {
            stopAndCancel();
        }

    }
    return super.onStartCommand(intent, flags, startId);
}