import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RemoteViews.RemoteView;
import java.util.TimeZone;
/**
* This widget display an analogic clock with two hands for hours and
* minutes.
*
* @attr ref android.R.styleable#AnalogClock_dial
* @attr ref android.R.styleable#AnalogClock_hand_hour
* @attr ref android.R.styleable#AnalogClock_hand_minute
*/
@RemoteView
public class AnalogClock extends View {
private Time mCalendar;
private Drawable mHourHand;//定义时针
private Drawable mMinuteHand;//定义分针
private Drawable mDial;//定义表盘
private int mDialWidth;//定义表盘的宽度
private int mDialHeight;//定义表盘的高度
private boolean mAttached;//定义是否是附着的view
private final Handler mHandler = new Handler();//handeler用来发送和处理消息,这里用来更新时间
private float mMinutes;//存储分钟的时间变量
private float mHour;//存储小时的时间变量
private boolean mChanged;//表示时间是否发生改变
//构造方法
public AnalogClock(Context context) {
this(context, null);
}
//构造方法
public AnalogClock(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
//构造方法
public AnalogClock(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
Resources r = mContext.getResources();//获得当前Context中/res目录下的资源
//定义一个数组,用来存放obtainStyledAttributes(AttributeSet, int[], int, int)获得的类型值
context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.AnalogClock, defStyle, 0);
//相当于Resource.getDrawble,从styleable中获得dial的图片资源
mDial = a.getDrawable(com.android.internal.R.styleable.AnalogClock_dial);
if (mDial == null) {//如果找不到图片资源,则从/res/drawble下面寻找图片资源,下同
mDial = r.getDrawable(com.android.internal.R.drawable.clock_dial);}
mHourHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_hour);
if (mHourHand == null) {
mHourHand = r.getDrawable(com.android.internal.R.drawable.clock_hand_hour);
}
mMinuteHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_minute);
if (mMinuteHand == null) {
mMinuteHand = r.getDrawable(com.android.internal.R.drawable.clock_hand_minute);
}
mCalendar = new Time();//初始化,获得当前的时间
mDialWidth = mDial.getIntrinsicWidth();//获得mDial的原始宽度
mDialHeight = mDial.getIntrinsicHeight();//获得mDial的原始高度
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!mAttached) {//如果没有附着view
mAttached = true;
//声明意图(消息)过滤器,过滤类型为action,获得表针,时间,时区改变的信息
filter.addAction(Intent.ACTION_TIME_TICK);//添加一个表针移动的action
filter.addAction(Intent.ACTION_TIME_CHANGED);//添加一个时间改变的action
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);//添加一个时区改变action
//注册mIntentReceiver,接受filter信息
getContext().registerReceiver(mIntentReceiver, filter, null, mHandler);
}
// NOTE: It's safe to do these after registering the receiver since the receiver always runs
// in the main thread, therefore the receiver can't run before this method returns.
// The time zone may have changed while the receiver wasn't registered, so update the Time
mCalendar = new Time();//当receiver未注册时,时区可能已经改变,所以要更新当前时间
// Make sure we update to the current time
onTimeChanged();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {//如果有附着窗口
getContext().unregisterReceiver(mIntentReceiver);//移除前面注册的mIntentReceiver
mAttached = false;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);//获得MeasureSpec(测量规范)中的width的模式
int widthSize = MeasureSpec.getSize(widthMeasureSpec);//获得MeasureSpec(测量规范)中的width大小
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
float hScale = 1.0f;//水平的放缩规模
float vScale = 1.0f;//垂直方向的放缩规模
//如果widthMode不是指定的模式,并且widthSize < mDialWidth,则需要将view放缩,即扩大view尺寸
if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mDialWidth) {
hScale = (float) widthSize / (float) mDialWidth;
}
if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mDialHeight) {
vScale = (float )heightSize / (float) mDialHeight;
}
float scale = Math.min(hScale, vScale);//选择最小的放缩规模
//测量图片的高度和宽度,并存储之
setMeasuredDimension(resolveSizeAndState((int) (mDialWidth * scale), widthMeasureSpec, 0),
resolveSizeAndState((int) (mDialHeight * scale), heightMeasureSpec, 0));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mChanged = true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
boolean changed = mChanged;
if (changed) {
mChanged = false;
}
int availableWidth = mRight - mLeft;//availableWidth是整个屏幕的宽度,mRight是最右边的端点值,mLeft是最右边的端点值
int availableHeight = mBottom - mTop;//avaailableHeight是整个屏幕的高度,mBottom是屏幕最低端的端点值,mTop是最上端端点值
//(x,y)是屏幕的中心点的坐标
int x = availableWidth / 2;
int y = availableHeight / 2;
final Drawable dial = mDial;
int w = dial.getIntrinsicWidth();//获得dial的宽度
int h = dial.getIntrinsicHeight();//获得dial的高度
boolean scaled = false;
if (availableWidth < w || availableHeight < h) {//如果dial的宽度和高度大于屏幕的高度和宽度,就要进行重新绘制
scaled = true;
float scale = Math.min((float) availableWidth / (float) w,
(float) availableHeight / (float) h);//获得超出屏幕大小的比例
canvas.scale(scale, scale, x, y);//扩大
}
if (changed) {//设置dial的边界,将dail放在view的正中间
dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
}
dial.draw(canvas);//在canvas上画出dial
canvas.save();//dial画完之后保存
canvas.rotate(mHour / 12.0f * 360.0f, x, y);//让时针绕点(x,y)旋转起来,mHour / 12.0f * 360.0f是时针旋转的角度
final Drawable hourHand = mHourHand;
if (changed) {
w = hourHand.getIntrinsicWidth();//获得时针图片的宽度
h = hourHand.getIntrinsicHeight();//获得时针图片的高度,下同
hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));//设置时针的边界,将时针也放置在view的中间
}
hourHand.draw(canvas);//绘制时针
canvas.restore();//remove all modifications to the matrix/clip state since the last save call(取消上一次的保存)
canvas.save();//重新保存
canvas.rotate(mMinutes / 60.0f * 360.0f, x, y);//让分针绕点(x,y)旋转,mMinutes / 60.0f * 360.0f是分针的旋转角度
final Drawable minuteHand = mMinuteHand;
if (changed) {
w = minuteHand.getIntrinsicWidth();//获得分针的宽度
h = minuteHand.getIntrinsicHeight();//获得分针的高度
minuteHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));//设置分针的边界,将其放在view的中间位置,即dial图片的中心在点(x,y)位置
}
minuteHand.draw(canvas);
canvas.restore();
if (scaled) {
canvas.restore();
}
}
private void onTimeChanged() {
mCalendar.setToNow();//获得当前的时间
int hour = mCalendar.hour;//获得当前时间的小时
int minute = mCalendar.minute;//获得当前时间的分钟
int second = mCalendar.second;//获得当前时间的秒
mMinutes = minute + second / 60.0f;//动态的显示没经过一秒钟时,mMinutes的值
mHour = hour + mMinutes / 60.0f;
mChanged = true;
updateContentDescription(mCalendar);
}
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {//如果时区发生改变,就要更新时区
String tz = intent.getStringExtra("time-zone");
mCalendar = new Time(TimeZone.getTimeZone(tz).getID());
}
onTimeChanged();
invalidate();//使整个窗口客户区无效 ,Invalidate()之后:...OnPaint()->OnPrepareDC()->OnDraw()
}
};
private void updateContentDescription(Time time) {
final int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR;
String contentDescription = DateUtils.formatDateTime(mContext,//按照当地习俗转换日期或时间格式(MM:SS或HH:MM:SS)
time.toMillis(false), flags);
setContentDescription(contentDescription);
}
}