packagecom.test;importjava.util.Calendar;importandroid.content.Context;importandroid.content.res.Resources;importandroid.database.ContentObserver;importandroid.os.Handler;importandroid.os.SystemClock;importandroid.provider.Settings;importandroid.text.format.DateFormat;importandroid.util.AttributeSet;/*** 自定义DigitalClock输出格式
*@author农民伯伯
**/publicclassDigitalClockextendsandroid.widget.DigitalClock {
Calendar mCalendar;privatefinalstaticString m12="h:mm aa";//h:mm:ss aaprivatefinalstaticString m24="k:mm";//k:mm:ssprivateFormatChangeObserver mFormatChangeObserver;privateRunnable mTicker;privateHandler mHandler;privatebooleanmTickerStopped=false;
String mFormat;publicDigitalClock(Context context) {super(context);
initClock(context);
}publicDigitalClock(Context context, AttributeSet attrs) {super(context, attrs);
initClock(context);
}privatevoidinitClock(Context context) {
Resources r=context.getResources();if(mCalendar==null) {
mCalendar=Calendar.getInstance();
}
mFormatChangeObserver=newFormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI,true, mFormatChangeObserver);
setFormat();
}
@OverrideprotectedvoidonAttachedToWindow() {
mTickerStopped=false;super.onAttachedToWindow();
mHandler=newHandler();/*** requests a tick on the next hard-second boundary*/mTicker=newRunnable() {publicvoidrun() {if(mTickerStopped)return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();longnow=SystemClock.uptimeMillis();longnext=now+(1000-now%1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
@OverrideprotectedvoidonDetachedFromWindow() {super.onDetachedFromWindow();
mTickerStopped=true;
}/*** Pulls 12/24 mode from system settings*/privatebooleanget24HourMode() {returnandroid.text.format.DateFormat.is24HourFormat(getContext());
}privatevoidsetFormat() {if(get24HourMode()) {
mFormat=m24;
}else{
mFormat=m12;
}
}privateclassFormatChangeObserverextendsContentObserver {publicFormatChangeObserver() {super(newHandler());
}
@OverridepublicvoidonChange(booleanselfChange) {
setFormat();
}
}
}