Example usage for android.text.format Time normalize

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

Introduction

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

Prototype

public long normalize(boolean ignoreDst) 

Source Link

Document

Ensures the values in each field are in range.

Usage

From source file:Main.java

public static long convertStrTimeToLong(String time_str) {
    /* input time string should have 
     *    - RFC 2445 DATETIM type: "%Y%m%dT%H%M%S"
     *///from ww w  .j ava2 s  .c  om
    Time time = new Time();
    time.parse(time_str);
    return time.normalize(false);
}

From source file:Main.java

public static Time getLastTime(Time time) {
    time.monthDay = time.getActualMaximum(Time.MONTH_DAY);
    time.normalize(true);
    return time;/*  w w w  . j  a va2s.  c o  m*/
}

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

/**
 * Queries events starting within a fixed interval from now.
 *///from   ww  w  .j a  va2  s .  co  m
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:Main.java

public static long getTime(Time tm, int hourOfDay, int minute) {
    // Cache the member variables locally to avoid inner class overhead.
    tm.hour = hourOfDay;/* w  w  w.jav a 2s. c om*/
    tm.minute = minute;

    // Cache the millis so that we limit the number of calls to
    // normalize() and toMillis(), which are fairly expensive.
    long millis = tm.normalize(true);
    return millis;
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

@SuppressLint("NewApi")
public static void addToCalender(Context context, Lecture l) {
    Intent intent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);

    intent.putExtra(CalendarContract.Events.TITLE, l.title);
    intent.putExtra(CalendarContract.Events.EVENT_LOCATION, l.room);

    long when;//from w  w  w  .ja  v  a  2 s  . c  om
    if (l.dateUTC > 0) {
        when = l.dateUTC;
    } else {
        Time time = l.getTime();
        when = time.normalize(true);
    }
    intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, when);
    intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, when + (l.duration * 60000));
    final String description = getCalendarDescription(context, l);
    intent.putExtra(CalendarContract.Events.DESCRIPTION, description);
    try {
        context.startActivity(intent);
        return;
    } catch (ActivityNotFoundException e) {
    }
    intent.setAction(Intent.ACTION_EDIT);
    try {
        context.startActivity(intent);
        return;
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, R.string.add_to_calendar_failed, Toast.LENGTH_LONG).show();
    }
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) {
    int[] alarm_times = { 0, 5, 10, 15, 30, 45, 60 };
    long when;//w w w .j ava  2  s  .  c  o  m
    Time time;
    long startTime;
    long startTimeInSeconds = lecture.dateUTC;

    if (startTimeInSeconds > 0) {
        when = startTimeInSeconds;
        startTime = startTimeInSeconds;
        time = new Time();
    } else {
        time = lecture.getTime();
        startTime = time.normalize(true);
        when = time.normalize(true);
    }
    long alarmTimeDiffInSeconds = alarm_times[alarmTimesIndex] * 60 * 1000;
    when -= alarmTimeDiffInSeconds;

    // DEBUG
    // when = System.currentTimeMillis() + (30 * 1000);

    time.set(when);
    MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id);
    intent.putExtra(BundleKeys.ALARM_DAY, lecture.day);
    intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title);
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);
    intent.setAction(AlarmReceiver.ALARM_LECTURE);

    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    // Set new alarm
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent);

    int alarmTimeInMin = alarm_times[alarmTimesIndex];

    // write to DB

    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);

    SQLiteDatabase db = alarmDB.getWritableDatabase();

    // delete any previous alarms of this lecture
    try {
        db.beginTransaction();
        db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title);
        values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin);
        values.put(AlarmsTable.Columns.TIME, when);
        DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
        values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when)));
        values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime);
        values.put(AlarmsTable.Columns.DAY, lecture.day);

        db.insert(AlarmsTable.NAME, null, values);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
    } finally {
        db.endTransaction();
        db.close();
    }

    lecture.has_alarm = true;
}

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

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
@Override//  w ww  . j a  v  a2s.com
protected void onHandleIntent(Intent intent) {
    mAuthority = getString(R.string.org_dmfs_tasks_authority);

    final String action = intent.getAction();
    final Context context = this;

    if (intent.hasExtra(EXTRA_NOTIFICATION_ID)) {
        Uri taskUri = intent.getData();
        int notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.cancel(notificationId);

        if (ACTION_COMPLETE.equals(action)) {
            markCompleted(taskUri);

        } else if (intent.hasExtra(EXTRA_TASK_DUE) && intent.hasExtra(EXTRA_TIMEZONE)) {
            long due = intent.getLongExtra(EXTRA_TASK_DUE, -1);
            String tz = intent.getStringExtra(EXTRA_TIMEZONE);
            boolean allDay = intent.getBooleanExtra(EXTRA_ALLDAY, false);
            if (ACTION_DELAY_1H.equals(action)) {
                Time time = new Time(tz);
                time.set(due);
                time.allDay = false;
                time.hour++;
                time.normalize(true);
                delayTask(taskUri, time);
            } else if (ACTION_DELAY_1D.equals(action)) {
                if (tz == null) {
                    tz = "UTC";
                }
                Time time = new Time(tz);
                time.set(due);
                time.allDay = allDay;
                time.monthDay++;
                time.normalize(true);
                delayTask(taskUri, time);
            }

        }

    } else if (intent.hasExtra(NotificationActionUtils.EXTRA_NOTIFICATION_ACTION)) {

        /*
         * Grab the alarm from the intent. Since the remote AlarmManagerService fills in the Intent to add some extra data, it must unparcel the
         * NotificationAction object. It throws a ClassNotFoundException when unparcelling. To avoid this, do the marshalling ourselves.
         */
        final NotificationAction notificationAction;
        final byte[] data = intent.getByteArrayExtra(NotificationActionUtils.EXTRA_NOTIFICATION_ACTION);
        if (data != null) {
            final Parcel in = Parcel.obtain();
            in.unmarshall(data, 0, data.length);
            in.setDataPosition(0);
            notificationAction = NotificationAction.CREATOR.createFromParcel(in,
                    NotificationAction.class.getClassLoader());
        } else {
            return;
        }

        if (NotificationActionUtils.ACTION_UNDO.equals(action)) {
            NotificationActionUtils.cancelUndoTimeout(context, notificationAction);
            NotificationActionUtils.cancelUndoNotification(context, notificationAction);
            resendNotification(notificationAction);
        } else if (ACTION_COMPLETE.equals(action)) {
            // All we need to do is switch to an Undo notification
            NotificationActionUtils.createUndoNotification(context, notificationAction);
            NotificationActionUtils.registerUndoTimeout(this, notificationAction);
        } else {
            if (NotificationActionUtils.ACTION_UNDO_TIMEOUT.equals(action)
                    || NotificationActionUtils.ACTION_DESTRUCT.equals(action)) {
                // Process the action
                NotificationActionUtils.cancelUndoTimeout(this, notificationAction);
                NotificationActionUtils.processUndoNotification(this, notificationAction);
                processDesctructiveNotification(notificationAction);
            }
        }
    }

}

From source file:com.granita.tasks.groupings.BaseTaskViewDescriptor.java

protected void setDueDate(TextView view, ImageView dueIcon, Time dueDate, boolean isClosed) {
    if (view != null && dueDate != null) {
        Time now = mNow;
        if (now == null) {
            now = mNow = new Time();
        }/*from w  w  w  .  ja  v a 2 s  .  c o  m*/
        if (!now.timezone.equals(TimeZone.getDefault().getID())) {
            now.clear(TimeZone.getDefault().getID());
        }

        if (Math.abs(now.toMillis(false) - System.currentTimeMillis()) > 5000) {
            now.setToNow();
            now.normalize(true);
        }

        dueDate.normalize(true);

        view.setText(new DateFormatter(view.getContext()).format(dueDate, now, DateFormatContext.LIST_VIEW));
        if (dueIcon != null) {
            dueIcon.setVisibility(View.VISIBLE);
        }

        // highlight overdue dates & times, handle allDay tasks separately
        if ((!dueDate.allDay && dueDate.before(now) || dueDate.allDay
                && (dueDate.year < now.year || dueDate.yearDay <= now.yearDay && dueDate.year == now.year))
                && !isClosed) {
            view.setTextAppearance(view.getContext(), R.style.task_list_overdue_text);
        } else {
            view.setTextAppearance(view.getContext(), R.style.task_list_due_text);
        }
    } else if (view != null) {
        view.setText("");
        if (dueIcon != null) {
            dueIcon.setVisibility(View.GONE);
        }
    }
}

From source file:com.dgsd.android.ShiftTracker.Fragment.HoursAndIncomeSummaryFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
    Time time = new Time();
    time.setJulianDay(mJulianDay);//from   w  w w .ja  v a 2 s  . c o  m

    switch (id) {
    case LOADER_ID_MONTH: {
        time.month--;
        break;
    }
    case LOADER_ID_3_MONTH: {
        time.month -= 3;
        break;
    }
    case LOADER_ID_6_MONTH: {
        time.month -= 6;
        break;
    }
    case LOADER_ID_9_MONTH: {
        time.month -= 9;
        break;
    }
    case LOADER_ID_YEAR:
        time.year--;
        break;
    }

    time.normalize(true);
    return getLoaderBetween(TimeUtils.getJulianDay(time), mJulianDay);
}

From source file:pt.up.mobile.syncadapter.SigarraSyncAdapter.java

private void syncSchedule(Account account, SyncResult syncResult)
        throws JSONException, AuthenticationException, IOException {
    final User user = AccountUtils.getUser(getContext(), account.name);
    final String type;
    if (user.getType().equals(SifeupAPI.STUDENT_TYPE))
        type = SigarraContract.Schedule.STUDENT;
    else/*from   w  ww. j  av  a 2s .  c  om*/
        type = SigarraContract.Schedule.EMPLOYEE;
    final Long mondayMillis = DateUtils.firstDayofWeek();
    Time monday = new Time(DateUtils.TIME_REFERENCE);
    monday.set(mondayMillis);
    monday.normalize(false);
    String initialDay = monday.format("%Y%m%d");
    // Friday
    monday.set(DateUtils.moveDayofWeek(mondayMillis, 4));
    monday.normalize(false);
    String finalDay = monday.format("%Y%m%d");
    getSchedule(account, user.getUserCode(), type, initialDay, finalDay, SyncStates.KEEP, syncResult);
}