您的位置:首页 > 移动开发 > Android开发

Android中一个动态更新时间并显示的小例子

2014-06-09 16:39 239 查看
这是一个利用线程和Handler配合更新时间的小例子:

1.主Activity:

public class TestTimeChangedActivity extends Activity{
private TextView tvTime ;
private TimeReceiver receiver ;
Handler mHandler ;
private static final int FLUSH_TIME_STATE = 100;
private boolean timeFlush = true ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_layout) ;

tvTime = (TextView) this.findViewById(R.id.tv_times) ;

register() ;
setHandler();
new TimeThread().start() ;
}

//控制时间更新的线程
private class TimeThread extends Thread{

@Override
public void run() {
super.run();
while (timeFlush) {
mHandler.sendEmptyMessage(FLUSH_TIME_STATE) ;
}
}
}
//实际更新时间的Handler
private void setHandler() {
mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case FLUSH_TIME_STATE:
updateTime() ;
break;

default:
break;
}
};
} ;
}

//注册时间变化的广播
private void register() {
IntentFilter filter = new IntentFilter() ;
filter.addAction(Intent.ACTION_TIME_CHANGED) ;
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED) ;
receiver = new TimeReceiver() ;
this.registerReceiver(receiver, filter) ;
}

//时间变化之后更新时间
private class TimeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
updateTime() ;
}

}
//更新时间的函数
private void updateTime() {
SimpleDateFormat timeFormat = null;
boolean is24 = DateFormat.is24HourFormat(this);
if (!is24) {
timeFormat = new SimpleDateFormat("hh:mm a");
} else {
timeFormat = new SimpleDateFormat("HH:mm");
}
Date now = Calendar.getInstance().getTime();
tvTime.setText(timeFormat.format(now));

}

@Override
protected void onDestroy() {
super.onDestroy();
if (receiver != null) {
this.unregisterReceiver(receiver) ;
}
}
}
2.xml文件:time_layout

<?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" >

<TextView
android:id="@+id/tv_times"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: