在android中专门的时钟对象AnalogClock,在屏幕上实现一个时钟效果。
示例:xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/tp">
<AnalogClock
android:id="@+id/myAnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp"
android:textColor="@drawable/white"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="white">#FF1F0F</drawable>
</resources>
JAVA文件:
package com.wxample6.www;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.AnalogClock;
import android.widget.TextView;
public class AnalogClockActivity extends Activity {
//申明常数作为判别信息使用
protected static final int GUINOTIFIER = 0x1234;
//申明两个widget对象变量
private TextView mTextView;
private AnalogClock mAnalogClock;
//申明与时间相关的变量
public Calendar mCalendar;
public int mMinutes;
public int mHour;
//申明Handler与Thread变量
public Handler mHandler;
private Thread mClockThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView)findViewById(R.id.myTextView);
mAnalogClock = (AnalogClock)findViewById(R.id.myAnalogClock);
//通过Handler来接收线程传递的信息并更新TextView
mHandler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case AnalogClockActivity.GUINOTIFIER:
mTextView.setText(mHour + ":" + mMinutes);
break;
}
super.handleMessage(msg);
}
};
//通过运行线程来持续取得系统时间
mClockThread = new LooperThread();
mClockThread.start();
}
//改写Thread来持续获得时间
class LooperThread extends Thread{
public void run(){
super.run();
try{
do{
long time = System.currentTimeMillis();
final Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(time);
mHour = mCalendar.get(Calendar.HOUR);
mMinutes = mCalendar.get(Calendar.MINUTE);
//让进城休息一秒
Thread.sleep(1000);
//取得时间后发给Handler
Message m = new Message();
m.what = AnalogClockActivity.GUINOTIFIER;
AnalogClockActivity.this.mHandler.sendMessage(m);
}while( AnalogClockActivity.LooperThread.interrupted() == false);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
注意:AnalogClock上显示的时间就是系统时间,不要设置就可以自动显示
运行结果: