1. 程式人生 > 實用技巧 >Android 獲取系統時間以及實時重新整理時間

Android 獲取系統時間以及實時重新整理時間

  • 使用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/89511064Android開發中獲取系統時間的幾種種方式 byVindent-C

https://blog.csdn.net/u011397174/article/details/18354523android.intent.action.TIME_TICK by arieluc

移動開發叢書·Android Studio開發實戰:從零基礎到App上線歐陽燊著