-
使用date獲取系統時間:
private SimpleDateFormat simpleDateFormat; private Date date; //onCreate中 simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); date = new Date(System.currentTimeMillis());//獲取系統時間 currentTimeText.setValue(simpleDateFormat.format(date));
Date方法比較簡單,只需要一條語句:Date().toLocaleString(),就可以獲得整個的時間信息,並且格式規范,不用再組裝,可以直接顯示。缺點是如果想用另外一種格式顯示,或者只需要單個的時間信息,就比較麻煩。可以定義SimpleDateFormat,規定哪些信息顯示,哪些信息不顯示,如顯示年、月、日、小時、分鍾、星期幾
在開發過程中,通常很多人都習慣使用new Date()來獲取當前時間。new Date()所做的事情其實就是調用了System.currentTimeMillis()。如果僅僅是需要獲得毫秒數,那么完全可以使用System.currentTimeMillis()去代替new Date(),效率上會高一點。
Date date = new Date(); String time = date.toLocaleString(); Log.i("md", "時間time為: "+time); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒 E"); String sim = dateFormat.format(date); Log.i("md", "時間sim為: "+sim);01-01 03:31:31.458: I/md(18530): 時間time為: Jan 1, 2015 3:31:31 AM
01-01 03:31:31.459: I/md(18530): 時間sim為: 2015年-01月01日-03時31分31秒 Thu
————————————————
版權聲明:本文為CSDN博主「Vindent-C」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_41508747/article/details/89511064
-
實時刷新時間,通過系統廣播實現
系統每分鍾都會發送廣播Intent.ACTION_TIME_TICK
//onCreateView中 IntentFilter filter=new IntentFilter();//創建意圖過濾器對象 filter.addAction(Intent.ACTION_TIME_TICK);//為接收器指定action,使之用於接收同action的廣播 view.getContext().registerReceiver(receiver,filter);//動態注冊廣播接收器 //view.getContext是一個fragment中的context private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_TIME_TICK)) { //TODO更新時間 } } };
android.intent.action.TIME_TICK是一個受保護的Intent,只能被系統發出。它不能通過在AndroidManifest.xml文件中注冊(靜態注冊)來接收廣播,只能通過Context.registerReceiver()在代碼中動態注冊。
為提高安卓系統的安全性,從9.0開始,系統全面禁止靜態注冊的廣播,凡是靜態廣播在9.0系統中都不再有效,因此為了適配Android 9.0,靜態注冊的廣播都 要換成在代碼里聲明的動態廣播
參考:
https://blog.csdn.net/qq_41508747/article/details/89511064 Android開發中獲取系統時間的幾種種方式 by Vindent-C
https://blog.csdn.net/u011397174/article/details/18354523 android.intent.action.TIME_TICK by arieluc
移動開發叢書·Android Studio開發實戰:從零基礎到App上線 歐陽燊著