2013-02-12 72 views
2

檢查方法System.currentTimeMilllis()它說:測量長的時間間隔

This method shouldn't be used for measuring timeouts or other 
elapsed time measurements, as changing the system time can affect the results. 

和像SystemClock.elapsedRealTime(其他方式),如果重置系統復位

所以,如果我想衡量,以便及時無論用戶是否更改系統時間,每兩天執行一次特定操作,我如何測量它?

+0

可能重複:http://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime – 2013-02-12 12:48:44

+0

您應該檢查http://stackoverflow.com/questions/7677674/use-of -ntp-SERV冰從互聯網上獲得真正的時間。 – WarrenFaith 2013-02-12 12:53:19

回答

1

至於Measure long time intervals - 你可以運行一個計時器,更新第二的計數器,它不會依賴系統時間

1

試試這個:

private long difference ; 

//This should be saved from when 2 days is to be checked 
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs",MODE_WORLD_READABLE); 
     syncdate = myPrefs.getLong("difference", System.currentTimeMillis()); 

    String olddate = changeFormat(syncdate); 
    String newdate = changeFormat(System.currentTimeMillis());//This is the new date 
    difference = getDate(olddate, newdate); 


     public static String changeFormat(long date){ 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); 

      Date resultdate = new Date(date); 
      String format = sdf.format(resultdate); 
      return format; 
     } 

     public static long getDate(String firstdate,String SecondDate) 
     { 
      Calendar calendar1 = Calendar.getInstance(); 
      Calendar calendar2 = Calendar.getInstance(); 
      String arr[] =firstdate.split("/"); 
      String arr1[] = SecondDate.split("/"); 
      int sty =Integer.parseInt(arr[0]); 
      int stm = Integer.parseInt(arr[1]); 
      int std = Integer.parseInt(arr[2]); 
      int sty1 = Integer.parseInt(arr1[0]); 
      int stm1 = Integer.parseInt(arr1[1]); 
      int std1 = Integer.parseInt(arr1[2]); 

      calendar1.set(sty, stm, std); 
      calendar2.set(sty1, stm1, std1); 
      long milliseconds1 = calendar1.getTimeInMillis(); 
      long milliseconds2 = calendar2.getTimeInMillis(); 
      long diff = milliseconds2 - milliseconds1; 
      long diffDays = diff/(24 * 60 * 60 * 1000); 

      return diffDays; 

     }