实现一个很基础很必备的功能,获取系统时间日期。
首先理清思路:用一个类TimeAndDate来调用系统的时间日期,为了让项目看起来简单明了用另一个类来初始化年月日等所需参数,最后需要在主函数中刷新显示,这里需要说明的是在主函数中需要生命周期中的onResume()来实现设备与程序的交互,不然并不会显示出当前的时间日期,这也是我在整个项目里面所犯的错误。
布局文件中放了两个TextView,居中显示,然后在MainActivity中定义并初始化,接下来直接贴TimeAndDate和参数SystemTimeInfo的代码:
public class TimeAndDate {
private static TimeAndDate timeAndDate=null;
public static TimeAndDate getInfo(){
if(timeAndDate==null){
timeAndDate=new TimeAndDate();
}
return timeAndDate;
}
private SystemTimeInfo mTime=new SystemTimeInfo();
public SystemTimeInfo getSystemTimeAndDate(){
final Calendar calendar=Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
mTime.yearString=String.valueOf(calendar.get(Calendar.YEAR));//String类型转换成Integer
mTime.monthString=String.valueOf(calendar.get(Calendar.MONTH));
mTime.dayString=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
String dayOfWeek=String.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
if("1".equals(dayOfWeek)){
dayOfWeek="天";
}else if("2".equals(dayOfWeek)){
dayOfWeek="一";
}else if("3".equals(dayOfWeek)){
dayOfWeek="二";
}else if("4".equals(dayOfWeek)){
dayOfWeek="三";
}else if("5".equals(dayOfWeek)){
dayOfWeek="四";
}else if ("6".equals(dayOfWeek)) {
dayOfWeek="五";
}else if ("7".equals(dayOfWeek)) {
dayOfWeek="六";
}
mTime.weekDayString="星期"+dayOfWeek;
// 24小时制
SimpleDateFormat dateFormat24 = new SimpleDateFormat("HH:mm");
// 12小时制
SimpleDateFormat dateFormat12 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mTime.timeString=dateFormat24.format(Calendar.getInstance().getTime());
// mTime.timeString=dateFormat12.format(Calendar.getInstance().getTime());
return mTime;
}
}public class SystemTimeInfo {
public String yearString;
public String monthString;
public String dayString;
public String weekDayString;
public String timeString;
}
注意,这里使用到时区,所以要在Mainifest中添加: <uses-permission android:name="android.permission.SET_TIME_ZONE"/>,而且使用ValueOf方法将String型变量转换为Integer类型。
回到MainActivity中,首先更新TextView,如下:
private void refreshDateAndTime(){
SystemTimeInfo time=TimeAndDate.getInfo().getSystemTimeAndDate();
timeTextView.setText(time.timeString);
dateTextView.setText(time.yearString+"年"+time.monthString+"月"+time.dayString+"日"+time.weekDayString);
}
然后在onResume()中调用refreshDateAndTime(),接下来使用发送广播:
private final BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action=intent.getAction();
int timeCurrent = 0;
if(action.equals(Intent.ACTION_TIME_TICK)){
refreshDateAndTime();
timeCurrent++;
if(timeCurrent>0){
timeCurrent=0;
}
}
}
};
其中每过一分钟更新一次时间,至此,运行程序,显示当前设备的系统时间日期。