Example usage for android.text.format Time Time

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

Introduction

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

Prototype

public Time() 

Source Link

Document

Construct a Time object in the default timezone.

Usage

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

/**
 * Queries events starting within a fixed interval from now.
 *///from   w  ww .j  a v a 2s . c  om
private static Cursor queryUpcomingEvents(Context context, ContentResolver contentResolver,
        long currentMillis) {
    Time time = new Time();
    time.normalize(false);
    long localOffset = time.gmtoff * 1000;
    final long localStartMin = currentMillis;
    final long localStartMax = localStartMin + EVENT_LOOKAHEAD_WINDOW_MS;
    final long utcStartMin = localStartMin - localOffset;
    final long utcStartMax = utcStartMin + EVENT_LOOKAHEAD_WINDOW_MS;

    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context,
            Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        //If permission is not granted then just return.
        Log.d(TAG, "Manifest.permission.READ_CALENDAR is not granted");
        return null;
    }

    // Expand Instances table range by a day on either end to account for
    // all-day events.
    Uri.Builder uriBuilder = Instances.CONTENT_URI.buildUpon();
    ContentUris.appendId(uriBuilder, localStartMin - DateUtils.DAY_IN_MILLIS);
    ContentUris.appendId(uriBuilder, localStartMax + DateUtils.DAY_IN_MILLIS);

    // Build query for all events starting within the fixed interval.
    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("(");
    queryBuilder.append(INSTANCES_WHERE);
    queryBuilder.append(") OR (");
    queryBuilder.append(INSTANCES_WHERE);
    queryBuilder.append(")");
    String[] queryArgs = new String[] {
            // allday selection
            "1", /* visible = ? */
            String.valueOf(utcStartMin), /* begin >= ? */
            String.valueOf(utcStartMax), /* begin <= ? */
            "1", /* allDay = ? */

            // non-allday selection
            "1", /* visible = ? */
            String.valueOf(localStartMin), /* begin >= ? */
            String.valueOf(localStartMax), /* begin <= ? */
            "0" /* allDay = ? */
    };

    Cursor cursor = contentResolver.query(uriBuilder.build(), INSTANCES_PROJECTION, queryBuilder.toString(),
            queryArgs, null);
    return cursor;
}

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

public static void sendDueAlarmNotification(Context context, String title, Uri taskUri, int notificationId,
        long dueDate, boolean dueAllDay, String timezone, boolean silent) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    String dueString = "";
    if (dueAllDay) {
        dueString = context.getString(R.string.notification_task_due_today);
    } else {/*from  w w w  . j a v  a2  s .  com*/
        dueString = context.getString(R.string.notification_task_due_date, new DateFormatter(context)
                .format(makeTime(dueDate, dueAllDay), DateFormatContext.NOTIFICATION_VIEW));
    }

    // build notification
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(context.getString(R.string.notification_task_due_title, title))
            .setContentText(dueString);

    // dismisses the notification on click
    mBuilder.setAutoCancel(true);

    // set status bar test
    mBuilder.setTicker(title);

    // enable light, sound and vibration
    if (silent) {
        mBuilder.setDefaults(0);
    } else {
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
    }

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(Intent.ACTION_VIEW);
    resultIntent.setData(taskUri);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // add actions
    if (android.os.Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
        // delay notification
        mBuilder.addAction(NotificationActionIntentService.getDelay1dAction(context, notificationId, taskUri,
                dueDate, timezone, dueAllDay));

        // complete action
        NotificationAction completeAction = new NotificationAction(
                NotificationActionIntentService.ACTION_COMPLETE, R.string.notification_action_completed,
                notificationId, taskUri, dueDate);
        mBuilder.addAction(NotificationActionIntentService.getCompleteAction(context,
                NotificationActionUtils.getNotificationActionPendingIntent(context, completeAction)));
    }

    // set displayed time
    if (dueAllDay) {
        Time now = new Time();
        now.setToNow();
        now.set(0, 0, 0, now.monthDay, now.month, now.year);
        mBuilder.setWhen(now.toMillis(true));
    } else {
        mBuilder.setWhen(dueDate);
    }

    mBuilder.setContentIntent(resultPendingIntent);
    notificationManager.notify(notificationId, mBuilder.build());
}

From source file:be.ac.ucl.lfsab1509.llncampus.services.AlarmService.java

/**
 * Load the next event in the nextEvent variable.
 *///from  ww  w  . j  a  v a 2s.c  o  m
private static void loadNextEvent() {
    Log.d("AlarmService", "nextEvent update");
    long precTime;
    if (nextEvent == null) {
        Time currentDate = new Time();
        currentDate.setToNow();
        Log.d("AlarmService", "currentDate.toMilis= " + currentDate.toMillis(false));
        precTime = currentDate.toMillis(false);
    } else {
        precTime = nextEvent.getBeginTime().toMillis(false);
    }
    Cursor c = LLNCampus.getDatabase()
            .sqlRawQuery("SELECT h.TIME_BEGIN, h.TIME_END, h.COURSE, h.ROOM, c.NAME "
                    + "FROM Horaire as h, Courses as c " + "WHERE h.COURSE = c.CODE AND TIME_BEGIN > "
                    + precTime + " " + "ORDER BY TIME_BEGIN ASC LIMIT 1");
    c.moveToFirst();
    try {
        nextEvent = new Event(c.getLong(0), c.getLong(1));
        nextEvent.addDetail(Event.COURSE, c.getString(2));
        nextEvent.addDetail(Event.ROOM, c.getString(3));
        nextEvent.addDetail(Event.TITLE, c.getString(4));
        c.close();
    } catch (CursorIndexOutOfBoundsException e) // No event yet.
    {
        resetNextEvent();
    }
}

From source file:com.android.calendar.event.EditEventActivity.java

private EventInfo getEventInfoFromIntent(Bundle icicle) {
    EventInfo info = new EventInfo();
    long eventId = -1;
    Intent intent = getIntent();/*  w ww .  j a v a2  s  . co m*/
    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);
    }

    boolean allDay = intent.getBooleanExtra(EXTRA_EVENT_ALL_DAY, false);

    long begin = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1);
    long end = intent.getLongExtra(EXTRA_EVENT_END_TIME, -1);
    if (end != -1) {
        info.endTime = new Time();
        if (allDay) {
            info.endTime.timezone = Time.TIMEZONE_UTC;
        }
        info.endTime.set(end);
    }
    if (begin != -1) {
        info.startTime = new Time();
        if (allDay) {
            info.startTime.timezone = Time.TIMEZONE_UTC;
        }
        info.startTime.set(begin);
    }
    info.id = eventId;
    info.eventTitle = intent.getStringExtra(Events.TITLE);
    info.calendarId = intent.getLongExtra(Events.CALENDAR_ID, -1);

    if (allDay) {
        info.extraLong = CalendarController.EXTRA_CREATE_ALL_DAY;
    } else {
        info.extraLong = 0;
    }
    return info;
}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Generates a relatively unique path to use as a temporary directory.
 * /*from   www  .j a v a 2 s  .  c  o  m*/
 * @return
 */
public static String generateTempPath() {
    Time now = new Time();
    now.setToNow();
    return "tmp-" + now.toMillis(false) + "/";
}

From source file:com.example.android.sunshine.app.Utility.java

/**
 * Given a day, returns just the name to use for that day.
 * E.g "today", "tomorrow", "wednesday".
 *
 * @param context Context to use for resource localization
 * @param dateInMillis The date in milliseconds
 * @return// w w  w.j  av  a  2  s . c o m
 */
public static String getDayName(Context context, long dateInMillis) {
    // If the date is today, return the localized version of "Today" instead of the actual
    // day name.

    Time t = new Time();
    t.setToNow();
    int julianDay = Time.getJulianDay(dateInMillis, t.gmtoff);
    int currentJulianDay = Time.getJulianDay(System.currentTimeMillis(), t.gmtoff);
    if (julianDay == currentJulianDay) {
        return context.getString(R.string.today);
    } else if (julianDay == currentJulianDay + 1) {
        return context.getString(R.string.tomorrow);
    } else {
        Time time = new Time();
        time.setToNow();
        // Otherwise, the format is just the day of the week (e.g "Wednesday".
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
        return dayFormat.format(dateInMillis);
    }
}

From source file:org.dmfs.tasks.notification.NotificationActionUtils.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void sendDueAlarmNotification(Context context, String title, Uri taskUri, int notificationId,
        long dueDate, boolean dueAllDay, String timezone, boolean silent) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    String dueString = "";
    if (dueAllDay) {
        dueString = context.getString(R.string.notification_task_due_today);
    } else {/*from  ww w.  ja v  a 2 s. c o  m*/
        dueString = context.getString(R.string.notification_task_due_date,
                formatTime(context, makeTime(dueDate, dueAllDay)));
    }

    // build notification
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(context.getString(R.string.notification_task_due_title, title))
            .setContentText(dueString);

    // color
    mBuilder.setColor(context.getResources().getColor(R.color.colorPrimary));

    // dismisses the notification on click
    mBuilder.setAutoCancel(true);

    // set high priority to display heads-up notification
    if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    // set status bar test
    mBuilder.setTicker(title);

    // enable light, sound and vibration
    if (silent) {
        mBuilder.setDefaults(0);
    } else {
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
    }

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(Intent.ACTION_VIEW);
    resultIntent.setData(taskUri);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // add actions
    if (android.os.Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
        // delay action
        mBuilder.addAction(NotificationUpdaterService.getDelay1dAction(context, notificationId, taskUri,
                dueDate, timezone, dueAllDay));

        // complete action
        NotificationAction completeAction = new NotificationAction(NotificationUpdaterService.ACTION_COMPLETE,
                R.string.notification_action_completed, notificationId, taskUri, dueDate);
        mBuilder.addAction(NotificationUpdaterService.getCompleteAction(context,
                NotificationActionUtils.getNotificationActionPendingIntent(context, completeAction)));
    }

    // set displayed time
    if (dueAllDay) {
        Time now = new Time();
        now.setToNow();
        now.set(0, 0, 0, now.monthDay, now.month, now.year);
        mBuilder.setWhen(now.toMillis(true));
    } else {
        mBuilder.setWhen(dueDate);
    }

    mBuilder.setContentIntent(resultPendingIntent);
    notificationManager.notify(notificationId, mBuilder.build());
}

From source file:be.ac.ucl.lfsab1509.llncampus.services.AlarmService.java

/**
 * Check if an event will occur and send a alert if needed.
 *///from w  ww . ja  v a  2  s  . c  o m
private void checkAlarm() {
    SharedPreferences preferences = new SecurePreferences(this);
    if (!preferences.getBoolean(SettingsActivity.COURSES_NOTIFY, false)) {
        Log.d("AlarmService", "Course notifications are disabled.");
        return;
    }

    if (Course.getList().size() != 0 && nextEvent == null) {
        loadNextEvent();
    }

    if (nextEvent != null) // If there is a next event, check if an alert should be sent.
    {

        int nbMin = LLNCampus.getIntPreference(SettingsActivity.NOTIFY_MINUTE, DEFAULT_NOTIFY_MINUTE, this);

        // Added computations if notifications depend on the position of the user.
        if (preferences.getBoolean(SettingsActivity.NOTIFY_WITH_GPS, false)) {
            Coordinates eventCoord = nextEvent.getCoordinates();
            if (eventCoord != null) {
                Coordinates currentCoord = LLNCampus.getGPS().getPosition();
                if (currentCoord != null) {
                    double dist = eventCoord.getDistance(currentCoord);
                    if (dist > MIN_DISTANCE
                            && dist < LLNCampus.getIntPreference(SettingsActivity.NOTIFY_MAX_DISTANCE,
                                    DEFAULT_MAX_DISTANCE, this)) {
                        int speedInKmPerHour = LLNCampus.getIntPreference(SettingsActivity.NOTIFY_SPEED_MOVE,
                                DEFAULT_NOTIFY_SPEED, this);
                        int speedMetersPerMinute = speedInKmPerHour * 1000 / 60;
                        nbMin = (int) (dist / speedMetersPerMinute) + LLNCampus
                                .getIntPreference(SettingsActivity.NOTIFY_MORE_TIME, DEFAULT_MORE_TIME, this);
                    }
                }
            }
        }
        Time currentTime = new Time();
        currentTime.setToNow();

        // Check if a notification should be sent.
        if (Course.getList().size() != 0 && nextEvent.getBeginTime().toMillis(false) - nbMin * 60L * 1000L
                - currentTime.toMillis(false) < 0L) {
            sendAlert(nextEvent);
            loadNextEvent();
        }
    }
}

From source file:com.snaptic.api.SnapticAPI.java

/**
 * Java Android interface to the Snaptic API.
 *
 * @param String user snaptic username.//w  ww.j  a  va 2  s  . c  o m
 * @param String password password for account.
 */
public SnapticAPI(String user, String password) {
    String auth = user + ':' + password;
    basicUserAuth = "Basic " + new String(Base64.encodeBase64(auth.getBytes()));
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, USER_AGENT);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    httpClient = new DefaultHttpClient(params);

    try {
        @SuppressWarnings("unused")
        Field field = Build.VERSION.class.getDeclaredField("SDK_INT");

        if (Build.VERSION.SDK_INT >= 6) {
            // We can use Time & TimeFormatException on Android 2.0.1
            // (API level 6) or greater. It crashes the VM otherwise.
            timestamper = new Time();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:uk.co.alt236.floatinginfo.provider.generalinfo.GeneralInfoProvider.java

@Override
public void onLogShare() {
    final StringBuilder sb = new StringBuilder();
    sb.append(mUiManager.getSharePayload());

    final Time now = new Time();
    now.setToNow();//w w w  .  j  a  v  a 2  s.c  om

    final String ts = now.format3339(false);

    final Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject) + " " + ts);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(shareIntent);
}