下面列出了怎么用android.text.format.Time的API类实例代码及写法,或者点击链接到github查看源代码。
private String getTaskTitleDueString(Cursor c, boolean isAllDay)
{
if (isAllDay)
{
return getString(R.string.dashclock_widget_title_due_expanded_allday, c.getString(c.getColumnIndex(Tasks.TITLE)));
}
else
{
TimeFieldAdapter timeFieldAdapter = new TimeFieldAdapter(Instances.DUE, Instances.TZ, Instances.IS_ALLDAY);
Time dueTime = timeFieldAdapter.get(c);
if (dueTime == null)
{
return null;
}
String dueTimeString = mDateFormatter.format(dueTime, DateFormatContext.DASHCLOCK_VIEW);
return getString(R.string.dashclock_widget_title_due_expanded, c.getString(c.getColumnIndex(Tasks.TITLE)), dueTimeString);
}
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(Color.BLACK);
mHandPaint = new Paint();
mHandPaint.setColor(Color.WHITE);
mHandPaint.setStrokeWidth(STROKE_WIDTH);
mHandPaint.setAntiAlias(true);
mHandPaint.setStrokeCap(Paint.Cap.ROUND);
mTime = new Time();
}
@Override
public Time apply(ContentSet currentValues, Time oldValue, Time newValue)
{
Time timeToShift = mTimeAdapter.get(currentValues);
if (timeToShift != null && newValue != null && oldValue != null)
{
boolean isAllDay = timeToShift.allDay;
timeToShift.set(timeToShift.toMillis(false) + (newValue.toMillis(false) - oldValue.toMillis(false)));
// ensure the event is still allday if is was allday before.
if (isAllDay)
{
timeToShift.set(timeToShift.monthDay, timeToShift.month, timeToShift.year);
}
mTimeAdapter.set(currentValues, timeToShift);
}
return newValue;
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(Color.BLACK);
final int backgroundResId = R.drawable.custom_background;
mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), backgroundResId);
mHandPaint = new Paint();
mHandPaint.setColor(Color.WHITE);
mHandPaint.setStrokeWidth(STROKE_WIDTH);
mHandPaint.setAntiAlias(true);
mHandPaint.setStrokeCap(Paint.Cap.ROUND);
mTime = new Time();
}
/**
* 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
*/
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);
}
}
public static String formatTime(Context context, long when) {
// TODO: DateUtils should make this easier
Time then = new Time();
then.set(when);
Time now = new Time();
now.setToNow();
int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL;
if (then.year != now.year) {
flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
} else if (then.yearDay != now.yearDay) {
flags |= DateUtils.FORMAT_SHOW_DATE;
} else {
flags |= DateUtils.FORMAT_SHOW_TIME;
}
return DateUtils.formatDateTime(context, when, flags);
}
public static String formatTime(Context context, long when) {
// TODO: DateUtils should make this easier
Time then = new Time();
then.set(when);
Time now = new Time();
now.setToNow();
int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL;
if (then.year != now.year) {
flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
} else if (then.yearDay != now.yearDay) {
flags |= DateUtils.FORMAT_SHOW_DATE;
} else {
flags |= DateUtils.FORMAT_SHOW_TIME;
}
return DateUtils.formatDateTime(context, when, flags);
}
@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();
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(Color.BLACK);
final int backgroundResId = R.drawable.custom_background;
mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), backgroundResId);
mHandPaint = new Paint();
mHandPaint.setColor(Color.WHITE);
mHandPaint.setStrokeWidth(STROKE_WIDTH);
mHandPaint.setAntiAlias(true);
mHandPaint.setStrokeCap(Paint.Cap.ROUND);
mHandPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, Color.BLACK);
mHandPaint.setStyle(Paint.Style.STROKE);
mTime = new Time();
}
private static long createCalendar(Account account, String name, int color){
ContentValues values = new ContentValues();
values.put(CalendarContract.Calendars.NAME, name);
values.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, name);
values.put(CalendarContract.Calendars.CALENDAR_COLOR, color);
values.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
values.put(CalendarContract.Calendars.OWNER_ACCOUNT, account.name);
values.put(CalendarContract.Calendars.ACCOUNT_NAME, account.name);
values.put(CalendarContract.Calendars.ACCOUNT_TYPE, account.type);
values.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_READ);
values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
values.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, Time.getCurrentTimezone());
Uri calSyncUri = CalendarContract.Calendars.CONTENT_URI.buildUpon()
.appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account.name)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, account.type)
.build();
Uri calUri = mContentResolver.insert(calSyncUri, values);
long calId = ContentUris.parseId(calUri);
return calId;
}
@Override
public void onClick(View v)
{
int id = v.getId();
Time time = mAdapter.get(mValues);
if (id == R.id.button_add_one_day)
{
time.monthDay++;
time.normalize(true);
}
else if (id == R.id.button_add_one_hour)
{
time.hour++;
time.normalize(false);
}
mAdapter.validateAndSet(mValues, time);
}
/**
* {@link Time} will eventually be replaced with {@link DateTime} in the project.
* This conversion function is only needed in the transition period.
*/
@VisibleForTesting
Time toTime(DateTime dateTime)
{
if (dateTime.isFloating() && !dateTime.isAllDay())
{
throw new IllegalArgumentException("Cannot support floating DateTime that is not all-day, can't represent it with Time");
}
// Time always needs a TimeZone (default ctor falls back to TimeZone.getDefault())
String timeZoneId = dateTime.getTimeZone() == null ? "UTC" : dateTime.getTimeZone().getID();
Time time = new Time(timeZoneId);
time.set(dateTime.getTimestamp());
// TODO Would using time.set(monthDay, month, year) be better?
if (dateTime.isAllDay())
{
time.allDay = true;
// This is needed as per time.allDay docs:
time.hour = 0;
time.minute = 0;
time.second = 0;
}
return time;
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(Color.BLACK);
mHandPaint = new Paint();
mHandPaint.setColor(Color.WHITE);
mHandPaint.setStrokeWidth(STROKE_WIDTH);
mHandPaint.setAntiAlias(true);
mHandPaint.setStrokeCap(Paint.Cap.ROUND);
mTime = new Time();
}
@Override
public Time getCustomDefault(ContentSet currentValues, Time genericDefault)
{
Time reference = mReferenceAdapter != null ? mReferenceAdapter.get(currentValues) : null;
boolean useReference = reference != null && !genericDefault.before(reference);
Time value = new Time(useReference ? reference : genericDefault);
if (value.allDay)
{
value.set(value.monthDay - (useReference ? 1 : 0), value.month, value.year);
}
else
{
value.minute--;
value.normalize(false);
value.second = 0;
value.minute = 0;
}
return value;
}
@Override
public Time getDefault(ContentSet values)
{
// create a new Time for the given time zone, falling back to the default time zone if none is given
String timezone = mTzField == null ? Time.TIMEZONE_UTC : values.getAsString(mTzField);
Time value = new Time(timezone == null ? TimeZone.getDefault().getID() : timezone);
value.setToNow();
Integer allDayInt = mAllDayField == null ? null : values.getAsInteger(mAllDayField);
if ((allDayInt != null && allDayInt != 0) || (mAllDayField == null && mAllDayDefault))
{
// make it an allday value
value.set(value.monthDay, value.month, value.year);
value.timezone = Time.TIMEZONE_UTC; // all-day values are saved in UTC
}
return value;
}
public static int day2TimeDay(int day) {
switch (day) {
case SU:
return Time.SUNDAY;
case MO:
return Time.MONDAY;
case TU:
return Time.TUESDAY;
case WE:
return Time.WEDNESDAY;
case TH:
return Time.THURSDAY;
case FR:
return Time.FRIDAY;
case SA:
return Time.SATURDAY;
default:
throw new RuntimeException("bad day of week: " + day);
}
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(Color.BLACK);
final int backgroundResId = R.drawable.custom_background;
mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), backgroundResId);
mHandPaint = new Paint();
mHandPaint.setColor(Color.WHITE);
mHandPaint.setStrokeWidth(STROKE_WIDTH);
mHandPaint.setAntiAlias(true);
mHandPaint.setStrokeCap(Paint.Cap.ROUND);
mHandPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, Color.BLACK);
mHandPaint.setStyle(Paint.Style.STROKE);
mTime = new Time();
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
//see https://developer.android.com/reference/android/support/wearable/watchface/WatchFaceStyle.Builder.html for more info on the methods use
//in the next command
setWatchFaceStyle(new WatchFaceStyle.Builder(BatmanWatchFaceService.this)
.setStatusBarGravity(Gravity.TOP | Gravity.END) //where the battery and connect icons shows.
.build());
Resources resources = BatmanWatchFaceService.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
bm_c = BitmapFactory.decodeResource(resources,R.drawable.batman2c);
bm_bw = BitmapFactory.decodeResource(resources,R.drawable.batman2bw);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(resources.getColor(R.color.digital_background));
mTextPaint_time = new Paint();
mTextPaint_time = createTextPaint(resources.getColor(R.color.digital_text));
mTextPaint_date = new Paint();
mTextPaint_date = createTextPaint(resources.getColor(R.color.digital_text));
mTime = new Time();
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
mHourHandBitmap = loadBitmaps(R.array.hourHandIds);
mMinuteHandBitmap = loadBitmaps(R.array.minuteHandIds);
mSecondsHandBitmap = loadBitmaps( R.array.secondHandIds );
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor( Color.parseColor("black") );
mTime = new Time();
mFilterPaint = new Paint();
mFilterPaint.setFilterBitmap(true);
initTickPaint();
}
public static int timeDay2Day(int day) {
switch (day) {
case Time.SUNDAY:
return SU;
case Time.MONDAY:
return MO;
case Time.TUESDAY:
return TU;
case Time.WEDNESDAY:
return WE;
case Time.THURSDAY:
return TH;
case Time.FRIDAY:
return FR;
case Time.SATURDAY:
return SA;
default:
throw new RuntimeException("bad day of week: " + day);
}
}
private JSONObject getIsDayLightSavingsTime(JSONArray options) throws GlobalizationError{
JSONObject obj = new JSONObject();
boolean dst = false;
try{
Date date = new Date((Long)options.getJSONObject(0).get(DATE));
//TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone();
TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());
dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings
return obj.put("dst",dst);
}catch(Exception ge){
throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
}
}
public void setMonthParams(HashMap<String, Integer> monthParams) {
if ((!monthParams.containsKey("month")) && (!monthParams.containsKey("year")))
throw new InvalidParameterException("You must specify the month and year for this view");
setTag(monthParams);
if (monthParams.containsKey("height")) {
this.mRowHeight = ((Integer) monthParams.get("height")).intValue();
if (this.mRowHeight < MIN_HEIGHT)
this.mRowHeight = MIN_HEIGHT;
}
if (monthParams.containsKey("selected_day"))
this.mSelectedDay = ((Integer) monthParams.get("selected_day")).intValue();
this.mMonth = ((Integer) monthParams.get("month")).intValue();
this.mYear = ((Integer) monthParams.get("year")).intValue();
Time time = new Time(Time.getCurrentTimezone());
time.setToNow();
this.mHasToday = false;
this.mToday = -1;
this.mCalendar.set(Calendar.MONTH, this.mMonth);
this.mCalendar.set(Calendar.YEAR, this.mYear);
this.mCalendar.set(Calendar.DAY_OF_MONTH, 1);
this.mDayOfWeekStart = this.mCalendar.get(Calendar.DAY_OF_WEEK);
if (monthParams.containsKey("week_start")) {
this.mWeekStart = ((Integer) monthParams.get("week_start")).intValue();
} else {
this.mWeekStart = this.mCalendar.getFirstDayOfWeek();
}
this.mNumCells = Utils.getDaysInMonth(this.mMonth, this.mYear);
for (int day = 0; day < this.mNumCells; day++) {
int monthDay = day + 1;
if (sameDay(monthDay, time)) {
this.mHasToday = true;
this.mToday = monthDay;
}
}
this.mNumRows = calculateNumRows();
}
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyTapFace.this)
.setAcceptsTapEvents(true) //turn on the tap events.
.build());
Resources resources = MyTapFace.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(resources.getColor(R.color.digital_background));
mTextPaint = new Paint();
mTextPaint = createTextPaint(resources.getColor(R.color.digital_text));
//for rec painting, mostly the same as text, except for fill/stroke
mRecPaint = new Paint();
mRecPaint = createTextPaint(resources.getColor(R.color.digital_text));
mRecPaint.setStyle(Paint.Style.STROKE);
mRecPaint.setStrokeWidth(strokewidth); //set the line size to be 5 "pixels".
mTime = new Time();
//initialize the rectangle for later use.
myRec = new Rect();
}
@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);
}
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);
}
/**
* Gets validity of ticket with time {@code t} in minutes.
*/
public static int getValidityMinutes(Time t) {
if (t == null) {
return -1;
}
final Time now = new Time();
now.setToNow();
now.switchTimezone(Time.getCurrentTimezone());
return (int)Math.ceil((t.toMillis(true) - now.toMillis(true)) / 1000d / 60d);
}
private static String getFormattedDate() {
Time time = new Time();
time.setToNow();
DateFormat.getDateInstance();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
/**
* Helper method to convert the database representation of the date into something to display
* to users. As classy and polished a user experience as "20140102" is, we can do better.
*
* @param context Context to use for resource localization
* @param dateInMillis The date in milliseconds
* @return a user-friendly representation of the date.
*/
public static String getFriendlyDayString(Context context, long dateInMillis) {
// The day string for forecast uses the following logic:
// For today: "Today, June 8"
// For tomorrow: "Tomorrow"
// For the next 5 days: "Wednesday" (just the day name)
// For all days after that: "Mon Jun 8"
Time time = new Time();
time.setToNow();
long currentTime = System.currentTimeMillis();
int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff);
int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff);
// If the date we're building the String for is today's date, the format
// is "Today, June 24"
if (julianDay == currentJulianDay) {
String today = context.getString(R.string.today);
int formatId = R.string.format_full_friendly_date;
return String.format(context.getString(
formatId,
today,
getFormattedMonthDay(context, dateInMillis)));
} else if ( julianDay < currentJulianDay + 7 ) {
// If the input date is less than a week in the future, just return the day name.
return getDayName(context, dateInMillis);
} else {
// Otherwise, use the form "Mon Jun 3"
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(dateInMillis);
}
}
/**
* 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;
}
/**
* reset header view.
*/
public void stopRefresh() {
Time time = new Time();
time.setToNow();
if (mPullRefreshing) {
mPullRefreshing = false;
resetHeaderHeight();
}
}