获取系统时间

来源:互联网 发布:超次元矩阵官网公测 编辑:程序博客网 时间:2024/06/12 21:12
one step: 通过广播接收系统时间
 private BroadcastReceiver receiver = new BroadcastReceiver() {
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action = intent.getAction();
   if(Intent.ACTION_TIME_CHANGED.equals(action)
     ||Intent.ACTION_TIME_TICK.equals(action)
     ||Intent.ACTION_TIMEZONE_CHANGED.equals(action)){
    if(handler!=null){
     handler.sendEmptyMessage(SYSTEM_TIME);
    }
   }
  }
 };
two step:在handler中显示时间
 timeText.setText(getSystemTime());
three step:获得系统时间的方法
 public String getSystemTime(){
  Calendar c = Calendar.getInstance();
        ContentResolver cv = getContentResolver();
        String strTimeFormat = android.provider.Settings.System.getString(cv,
                                           android.provider.Settings.System.TIME_12_24);
        SimpleDateFormat sdf = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE); 
        if("24".equalsIgnoreCase(strTimeFormat)){
          sdf.applyPattern("HH:mm"); 
        }else{
          sdf.applyPattern("hh:mm"); 
        }
     String time = sdf.format(c.getTimeInMillis());
  return time;
 
 }