2

I am using an alarm manager to start a service at particular time which is working fine, but for now if user changes the device time the service gets started according to that time.

Code:

calendar = new GregorianCalendar();
    calendar.setTimeInMillis(System.currentTimeMillis());
    cal = new GregorianCalendar();
    cal.add(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
    cal.set(Calendar.HOUR_OF_DAY, 11);
    cal.set(Calendar.MINUTE, 57);
    cal.set(Calendar.SECOND, calendar.get(Calendar.SECOND));
    cal.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND));
    cal.set(Calendar.DATE, calendar.get(Calendar.DATE));
    cal.set(Calendar.MONTH, calendar.get(Calendar.MONTH));

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Intent it = new Intent(MainActivity.this,Start_service_alarm.class);

    it.putExtra(Start_service_alarm.ACTION, Start_service_alarm.ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, it, 0);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 
karel
  • 5,489
  • 46
  • 45
  • 50
Edward Collins
  • 353
  • 3
  • 13

1 Answers1

0

The device only knows the currently set time (which can be automatically determined from an external internet or mobile network source, but can also be overridden by the user).

You need to have an external time provider that your application syncs with, probably sending its location so that the server can determine the correct time zone.

There are apis already available, e.g.: http://timezonedb.com/api, or you could roll your own

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37
  • If the device only "knows" the current time, as possibly set by the user, then I assume the alarm manager can only go off that time when deciding when to trigger alarms. Probably the best you could do would be to use an external time source to get the "real" time, and the set the alarm time based on the difference between "real" time and "device" time. (You possibly could offer to (re)set device time based on the external "real" time, but even if you don't _need_ user-confirmation to do this, you ought to ask). – TripeHound May 08 '15 at 10:39