我需要为我的布局实现数字时钟。我希望小时和分钟之间的点消失并每隔半秒左右重新出现一次。我复制了android时钟代码并对其进行了一些更改。这个想法是根据一些布尔值更改时间格式。但是由于某种原因,这种方法不起作用...如果您是并发大师,请帮助我!这是代码。
public class CustomDigitalClock extends TextView {
Calendar mCalendar;
private final static String m12 = "h:mm aa";
private final static String m24 = "k:mm";
private final static String m24space = "k mm";
private static final String LOG_TAG = "Clock";
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Runnable dotsRunner;
private Handler mHandler;
private AtomicBoolean dotsVisible;
private volatile boolean mTickerStopped = false;
String mFormat;
public CustomDigitalClock(Context context) {
super(context);
initClock(context);
}
public CustomDigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock(context);
}
private void initClock(Context context) {
Resources r = context.getResources();
dotsVisible = new AtomicBoolean();
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
@Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
if (dotsVisible.get()) {
setText(DateFormat.format(m24, mCalendar));
} else {
setText(DateFormat.format(m24space, mCalendar));
}
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
dotsRunner = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
dotsVisible.compareAndSet(true, false);
dotsVisible.compareAndSet(false, true);
} catch (InterruptedException ex) {
Log.e(LOG_TAG, ex.getMessage());
}
}
};
dotsRunner.run();
mTicker.run();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
/**
* Pulls 12/24 mode from system settings
*/
private boolean get24HourMode() {
return android.text.format.DateFormat.is24HourFormat(getContext());
}
private void setFormat() {
if (get24HourMode()) {
mFormat = m24;
} else {
mFormat = m12;
}
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
setFormat();
}
}
}