检查方法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 :(得分:1)
您应该使用类似AlarmManager.setInexactRepeating(int, long, long, android.app.PendingIntent)
方法的内容来定期启动您的操作
答案 1 :(得分:1)
对于Measure long time intervals
- 你可以运行一个更新第二个计数器的计时器,它不依赖于系统时间
答案 2 :(得分: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;
}