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() 会重置)

因此,如果我想测量时间以便每两天执行一次某个操作,而不管用户是否更改系统时间,我该如何测量呢?

4

3 回答 3

1

您应该使用类似AlarmManager.setInexactRepeating(int, long, long, android.app.PendingIntent)方法定期启动您的操作

于 2013-02-12T12:48:48.937 回答
1

至于Measure long time intervals-您可以运行一个更新秒计数器的计时器,它不依赖于系统时间

于 2013-02-12T12:54:43.693 回答
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;

        }
于 2013-02-12T12:55:59.727 回答