下面列出了android.text.format.Time#toMillis ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Save sum of calorie cache to DB
*/
public void saveCurrentActivityReport() {
int prevYear = mThisYear;
int prevMonth = mThisMonth;
int prevDay = mThisDay;
int prevHour = mThisHour;
// Push monthly report to DB
Time tempTime1 = new Time();
tempTime1.set(1, 0, 0, 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis1 = tempTime1.toMillis(true);
pushReportToDB(REPORT_TYPE_MONTH, millis1, prevYear, prevMonth, 1, 0);
// Push daily report to DB
Time tempTime2 = new Time();
tempTime2.set(1, 0, 0, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis2 = tempTime2.toMillis(true);
pushReportToDB(REPORT_TYPE_DAY, millis2, prevYear, prevMonth, prevDay, 0);
// Push hourly report to DB
Time tempTime3 = new Time();
tempTime3.set(1, 0, prevHour, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis3 = tempTime3.toMillis(true);
pushReportToDB(REPORT_TYPE_HOUR, millis3, prevYear, prevMonth, prevDay, prevHour);
}
@Override
protected void onHandleIntent(Intent intent) {
mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
// Query calendar events in the next 24 hours.
Time time = new Time();
time.setToNow();
long beginTime = time.toMillis(true);
time.monthDay++;
time.normalize(true);
long endTime = time.normalize(true);
List<Event> events = queryEvents(this, beginTime, endTime);
for (Event event : events) {
final PutDataMapRequest putDataMapRequest = event.toPutDataMapRequest();
if (mGoogleApiClient.isConnected()) {
Wearable.DataApi.putDataItem(
mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await();
} else {
Log.e(TAG, "Failed to send data item: " + putDataMapRequest
+ " - Client disconnected from Google Play Services");
}
}
mGoogleApiClient.disconnect();
}
public Boolean initConfig(String dataDir) {
if (_alreadyChecked)
return _previousCheckValue;
Time now = new Time();
now.setToNow();
// check for modifications only every X
if (_lastCheck.toMillis(true) + 3000 >= now.toMillis(true)) {
return _previousCheckValue;
}
String path = dataDir + "/" + _configFileName;
_hookTypes = readFirstLineOfFile(path);
if (_onlyCheckOnce)
_alreadyChecked = true;
_lastCheck.setToNow();
if (_hookTypes.isEmpty()) {
return (_previousCheckValue = false);
}
return (_previousCheckValue = true);
}
@android.view.RemotableViewMethod
public void setTime(long time) {
Time t = new Time();
t.set(time);
mTimeMillis = t.toMillis(false);
mTime = new Date(t.year-1900, t.month, t.monthDay, t.hour, t.minute, 0);
update();
}
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Time time = new Time();
time.set(0, mTimePicker.getCurrentMinute(),
mTimePicker.getCurrentHour(), mDatePicker.getDayOfMonth(),
mDatePicker.getMonth(), mDatePicker.getYear());
if (time.toMillis(true) < mMinTimeMillis) {
time.set(mMinTimeMillis);
} else if (time.toMillis(true) > mMaxTimeMillis) {
time.set(mMaxTimeMillis);
}
mTimePicker.setCurrentHour(time.hour);
mTimePicker.setCurrentMinute(time.minute);
}
@Override
public Boolean apply(ContentSet currentValues, Boolean oldValue, Boolean newValue)
{
Time time = mTimeAdapter.get(currentValues);
if (time != null)
{
if ((oldValue == null || !oldValue) && newValue != null && newValue)
{
// all-day has been enabled, ensure the given time is all-day
if (time.toMillis(false) % (24L * 60 * 60 * 1000L) != 0)
{
// not at 00:00:00 UTC yet
time.timezone = "UTC";
time.set(time.monthDay, time.month, time.year);
mTimeAdapter.set(currentValues, time);
}
}
// else if ((newValue == null || !newValue) && oldValue != null && oldValue)
// {
// ideally we move the time to 00:00:00 in the new time zone. Unfortunately we don't know the time zone at this point
// TODO: move the time to 00:00:00 in the new time zone, somehow
// }
}
return newValue;
}
public static long parse(String timeString)
throws IllegalArgumentException {
int date = 1;
int month = Calendar.JANUARY;
int year = 1970;
TimeOfDay timeOfDay;
Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
if (rfcMatcher.find()) {
date = getDate(rfcMatcher.group(1));
month = getMonth(rfcMatcher.group(2));
year = getYear(rfcMatcher.group(3));
timeOfDay = getTime(rfcMatcher.group(4));
} else {
Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
if (ansicMatcher.find()) {
month = getMonth(ansicMatcher.group(1));
date = getDate(ansicMatcher.group(2));
timeOfDay = getTime(ansicMatcher.group(3));
year = getYear(ansicMatcher.group(4));
} else {
throw new IllegalArgumentException();
}
}
// FIXME: Y2038 BUG!
if (year >= 2038) {
year = 2038;
month = Calendar.JANUARY;
date = 1;
}
Time time = new Time(Time.TIMEZONE_UTC);
time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
month, year);
return time.toMillis(false /* use isDst */);
}
@SuppressLint("SimpleDateFormat")
@Override
public void run() {
// 实时发送一个更新的广播
final String pref_key = "appwidget_news_refresh_time";
final long updatePeriod = 10 * 60 * 1000;
final long lastRefreshTime = Utils.getLong(this, pref_key, 0);
final long now = System.currentTimeMillis();
if (now - lastRefreshTime >= updatePeriod) {
// 10分钟内不执行重复的后台更新请求
Utils.putLong(this, pref_key, now);
Intent refreshNowIntent = new Intent(this, NewsAppWidgetProvider.class);
refreshNowIntent.setAction(NewsAppWidgetProvider.ACTION_REFRESH_AUTO);
sendBroadcast(refreshNowIntent);
}
Intent autoRefreshIntent = new Intent(this, NewsAppWidgetProvider.class);
autoRefreshIntent.setAction(NewsAppWidgetProvider.ACTION_REFRESH_AUTO);
PendingIntent pending = PendingIntent.getBroadcast(NewsWidgetService.this, 0, autoRefreshIntent, 0);
// 1*60秒更新一次
final long updateTime = 1 * 60 * 1000;
Time time = new Time();
long nowMillis = System.currentTimeMillis();
time.set(nowMillis + updateTime);
long updateTimes = time.toMillis(true);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
// Log.d(TAG, "request next update at " + updateTimes);
// Log.d(TAG, "refresh time: " + sdf.format(new Date()));
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, updateTimes, pending);
stopSelf();
}
public static long parse(String timeString)
throws IllegalArgumentException {
int date = 1;
int month = Calendar.JANUARY;
int year = 1970;
TimeOfDay timeOfDay;
Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
if (rfcMatcher.find()) {
date = getDate(rfcMatcher.group(1));
month = getMonth(rfcMatcher.group(2));
year = getYear(rfcMatcher.group(3));
timeOfDay = getTime(rfcMatcher.group(4));
} else {
Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
if (ansicMatcher.find()) {
month = getMonth(ansicMatcher.group(1));
date = getDate(ansicMatcher.group(2));
timeOfDay = getTime(ansicMatcher.group(3));
year = getYear(ansicMatcher.group(4));
} else {
throw new IllegalArgumentException();
}
}
// FIXME: Y2038 BUG!
if (year >= 2038) {
year = 2038;
month = Calendar.JANUARY;
date = 1;
}
Time time = new Time(Time.TIMEZONE_UTC);
time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
month, year);
return time.toMillis(false /* use isDst */);
}
public static long parse(String timeString) throws IllegalArgumentException {
int date = 1;
int month = Calendar.JANUARY;
int year = 1970;
TimeOfDay timeOfDay;
Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
if (rfcMatcher.find()) {
date = getDate(rfcMatcher.group(1));
month = getMonth(rfcMatcher.group(2));
year = getYear(rfcMatcher.group(3));
timeOfDay = getTime(rfcMatcher.group(4));
} else {
Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
if (ansicMatcher.find()) {
month = getMonth(ansicMatcher.group(1));
date = getDate(ansicMatcher.group(2));
timeOfDay = getTime(ansicMatcher.group(3));
year = getYear(ansicMatcher.group(4));
} else {
throw new IllegalArgumentException();
}
}
// FIXME: Y2038 BUG!
if (year >= 2038) {
year = 2038;
month = Calendar.JANUARY;
date = 1;
}
Time time = new Time(Time.TIMEZONE_UTC);
time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
month, year);
return time.toMillis(false /* use isDst */);
}
public static long parse(String timeString)
throws IllegalArgumentException {
int date = 1;
int month = Calendar.JANUARY;
int year = 1970;
TimeOfDay timeOfDay;
Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
if (rfcMatcher.find()) {
date = getDate(rfcMatcher.group(1));
month = getMonth(rfcMatcher.group(2));
year = getYear(rfcMatcher.group(3));
timeOfDay = getTime(rfcMatcher.group(4));
} else {
Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
if (ansicMatcher.find()) {
month = getMonth(ansicMatcher.group(1));
date = getDate(ansicMatcher.group(2));
timeOfDay = getTime(ansicMatcher.group(3));
year = getYear(ansicMatcher.group(4));
} else {
throw new IllegalArgumentException();
}
}
// FIXME: Y2038 BUG!
if (year >= 2038) {
year = 2038;
month = Calendar.JANUARY;
date = 1;
}
Time time = new Time(Time.TIMEZONE_UTC);
time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
month, year);
return time.toMillis(false /* use isDst */);
}
/**
* Parses the contents of an entry. If it encounters a title, summary, or link tag, hands them
* off to their respective "read" methods for processing. Otherwise, skips the tag.
*/
private Entry readEntry(XmlPullParser parser)
throws XmlPullParserException, IOException, ParseException {
parser.require(XmlPullParser.START_TAG, ns, "entry");
String id = null;
String title = null;
String link = null;
long publishedOn = 0;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("id")){
// Example: <id>urn:uuid:218AC159-7F68-4CC6-873F-22AE6017390D</id>
id = readTag(parser, TAG_ID);
} else if (name.equals("title")) {
// Example: <title>Article title</title>
title = readTag(parser, TAG_TITLE);
} else if (name.equals("link")) {
// Example: <link rel="alternate" type="text/html" href="http://example.com/article/1234"/>
//
// Multiple link types can be included. readAlternateLink() will only return
// non-null when reading an "alternate"-type link. Ignore other responses.
String tempLink = readTag(parser, TAG_LINK);
if (tempLink != null) {
link = tempLink;
}
} else if (name.equals("published")) {
// Example: <published>2003-06-27T12:00:00Z</published>
Time t = new Time();
t.parse3339(readTag(parser, TAG_PUBLISHED));
publishedOn = t.toMillis(false);
} else {
skip(parser);
}
}
return new Entry(id, title, link, publishedOn);
}
/**
* getGoogleLocation
*/
private String getGoogleLocation() {
Util.location = "Error";
try {
getNewLocation();
Thread.sleep(12000); // esperar
Double d1 = Util.locationReal.getLatitude();
Double d2 = Util.locationReal.getLongitude();
String latitude = Location.convert(d1,Location.FORMAT_DEGREES);
String longitude = Location.convert(d2,Location.FORMAT_DEGREES);
latitude = latitude.replace(",", ".");
longitude = longitude.replace(",", ".");
Util.location = "http://maps.google.com/maps?q=" + latitude + "," + longitude;
Util.logDebug("location: " + Util.location);
Time t = new Time();
t.setToNow();
Util.lastLocation = t.toMillis(false);
} catch(Exception e) {
Util.logDebug("Exception (getLocation): " + e.getMessage());
}
return Util.location;
}
@Override
public Time apply(ContentSet currentValues, Time oldValue, Time newValue)
{
Time reference = mReferenceAdapter.get(currentValues);
if (reference != null && newValue != null)
{
if (oldValue != null && !newValue.before(reference))
{
// try to shift the reference value
long diff = newValue.toMillis(false) - oldValue.toMillis(false);
if (diff > 0)
{
boolean isAllDay = reference.allDay;
reference.set(reference.toMillis(false) + diff);
// ensure the event is still allday if is was allday before.
if (isAllDay)
{
reference.set(reference.monthDay, reference.month, reference.year);
}
mReferenceAdapter.set(currentValues, reference);
}
}
if (!newValue.before(reference))
{
// constraint is still violated, so set reference to its default value
reference.set(mDefault.getCustomDefault(currentValues, newValue));
mReferenceAdapter.set(currentValues, reference);
}
}
return newValue;
}
public int getClampedSecondsWatchedSince(int since) {
Time now = new Time();
now.setToNow();
int secondsNow = (int) (now.toMillis(true) / 1000);
int maxSeconds = Math.max(secondsNow - since, 0);
return Math.min(maxSeconds, getSecondsWatched());
}
/**
* Contains the definition/requirement of when a {@link DateTime} and {@link Time} is considered equivalent in this project.
*/
private boolean isEquivalentDateTimeAndTime(DateTime dateTime, Time time)
{
// android.text.Time doesn't seem to store in millis precision, there is a 1000 multiplier used there internally
// when calculating millis, so we can only compare in this precision:
boolean millisMatch =
dateTime.getTimestamp() / 1000
==
time.toMillis(false) / 1000;
boolean yearMatch = dateTime.getYear() == time.year;
boolean monthMatch = dateTime.getMonth() == time.month;
boolean dayMatch = dateTime.getDayOfMonth() == time.monthDay;
boolean hourMatch = dateTime.getHours() == time.hour;
boolean minuteMatch = dateTime.getMinutes() == time.minute;
boolean secondsMatch = dateTime.getSeconds() == time.second;
boolean allDaysMatch = time.allDay == dateTime.isAllDay();
boolean timeZoneMatch =
(dateTime.isFloating() && dateTime.isAllDay() && time.timezone.equals("UTC"))
||
// This is the regular case with non-floating DateTime
(dateTime.getTimeZone() != null && time.timezone.equals(dateTime.getTimeZone().getID()));
return millisMatch
&& yearMatch
&& monthMatch
&& dayMatch
&& hourMatch
&& minuteMatch
&& secondsMatch
&& allDaysMatch
&& timeZoneMatch;
}
@Override
public void onContentChanged(ContentSet contentSet)
{
Time newValue = mAdapter.get(mValues);
if (mValues != null && newValue != null)
{
Date fullDate = new Date(newValue.toMillis(false));
String formattedTime;
if (!newValue.allDay)
{
mDefaultDateFormat.setTimeZone(mDefaultTimeZone);
mDefaultTimeFormat.setTimeZone(mDefaultTimeZone);
TimeZoneWrapper taskTimeZone = new TimeZoneWrapper(newValue.timezone);
formattedTime = mDateFormatter.format(newValue, DateFormatContext.DETAILS_VIEW);
if (!taskTimeZone.equals(mDefaultTimeZone) && !Time.TIMEZONE_UTC.equals(newValue.timezone) && mTimeZoneText != null)
{
/*
* The date has a time zone that is different from the default time zone, so show the original time too.
*/
mDefaultDateFormat.setTimeZone(taskTimeZone);
mDefaultTimeFormat.setTimeZone(taskTimeZone);
mTimeZoneText.setText(mDefaultDateFormat.format(fullDate) + " " + mDefaultTimeFormat.format(fullDate) + " "
+ taskTimeZone.getDisplayName(taskTimeZone.inDaylightTime(fullDate), TimeZone.SHORT));
mTimeZoneText.setVisibility(View.VISIBLE);
}
else
{
mTimeZoneText.setVisibility(View.GONE);
}
mAddOneHourButton.setVisibility(VISIBLE);
}
else
{
// all-day times are always in UTC
if (mTimeZoneText != null)
{
mTimeZoneText.setVisibility(View.GONE);
}
formattedTime = mDateFormatter.format(newValue, DateFormatContext.DETAILS_VIEW);
mAddOneHourButton.setVisibility(INVISIBLE);
}
mText.setText(formattedTime);
setVisibility(View.VISIBLE);
}
else
{
setVisibility(View.GONE);
}
}
private void configureConferenceDate() {
conferenceTime.set(second, minute, hour, monthDay, month, year);
conferenceTime.normalize(true);
long confMillis = conferenceTime.toMillis(true);
Time nowTime = new Time(Time.getCurrentTimezone());
nowTime.setToNow();
nowTime.normalize(true);
long nowMillis = nowTime.toMillis(true);
long milliDiff = confMillis - nowMillis;
new CountDownTimer(milliDiff, 1000) {
@Override
public void onTick(long millisUntilFinished) {
// decompose difference into days, hours, minutes and seconds
CountdownTimerActivity.this.mDisplayDays = (int) ((millisUntilFinished / 1000) / 86400);
CountdownTimerActivity.this.mDisplayHours = (int) (((millisUntilFinished / 1000) - (CountdownTimerActivity.this.mDisplayDays * 86400)) / 3600);
CountdownTimerActivity.this.mDisplayMinutes = (int) (((millisUntilFinished / 1000) - ((CountdownTimerActivity.this.mDisplayDays * 86400) + (CountdownTimerActivity.this.mDisplayHours * 3600))) / 60);
CountdownTimerActivity.this.mDisplaySeconds = (int) ((millisUntilFinished / 1000) % 60);
CountdownTimerActivity.this.mDaysWheel.setText(String.valueOf(CountdownTimerActivity.this.mDisplayDays));
CountdownTimerActivity.this.mDaysWheel.setProgress(CountdownTimerActivity.this.mDisplayDays);
CountdownTimerActivity.this.mHoursWheel.setText(String.valueOf(CountdownTimerActivity.this.mDisplayHours));
CountdownTimerActivity.this.mHoursWheel.setProgress(CountdownTimerActivity.this.mDisplayHours * 15);
CountdownTimerActivity.this.mMinutesWheel.setText(String.valueOf(CountdownTimerActivity.this.mDisplayMinutes));
CountdownTimerActivity.this.mMinutesWheel.setProgress(CountdownTimerActivity.this.mDisplayMinutes * 6);
Animation an = new RotateAnimation(0.0f, 90.0f, 250f, 273f);
an.setFillAfter(true);
CountdownTimerActivity.this.mSecondsWheel.setText(String.valueOf(CountdownTimerActivity.this.mDisplaySeconds));
CountdownTimerActivity.this.mSecondsWheel.setProgress(CountdownTimerActivity.this.mDisplaySeconds * 6);
}
@Override
public void onFinish() {
//TODO: this is where you would launch a subsequent activity if you'd like. I'm currently just setting the seconds to zero
Logger.d(TAG, "Timer Finished...");
CountdownTimerActivity.this.mSecondsWheel.setText("0");
CountdownTimerActivity.this.mSecondsWheel.setProgress(0);
}
}.start();
}
public static Date parse3339(String time) {
final Time t = new Time();
t.parse3339(time);
return new Date(t.toMillis(false));
}
protected Boolean isValidLocation(Location location) {
if (location == null)
return false;
Time now = new Time();
now.setToNow();
return (now.toMillis(true) - location.getTime()) <= TWO_MINUTES;
}