2

Checking the method System.currentTimeMilllis() it says:

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

and other method like SystemClock.elapsedRealTime() resets if the system is reset

So if I want to measure time in order to do a certain action once every two days regardless of whether user changes the system time, how can I measure it?

Addev
  • 31,819
  • 51
  • 183
  • 302

3 Answers3

1

You should use something like AlarmManager.setInexactRepeating(int, long, long, android.app.PendingIntent) method to launch your action at regular interval

nicopico
  • 3,606
  • 1
  • 28
  • 30
1

As for Measure long time intervals - you can run a timer that updates a second's counter, it will not depend on system time

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Try this:

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;

        }
user1744952
  • 508
  • 1
  • 3
  • 15