Search code examples
javaandroidtimebroadcastreceiver

Alarm app prevent Change of system time


My app works like this, the user write down a time in minutes, for example 40. Then the app will call an alarm in 40 minutes from now. It doesn't matter whether the app is active or running in background it still works.

My issue is this, since I use the method System.currentTimeMillis(); then it makes my app dependent on the system time. So if i change my system time in the settings, then my alarm app will not be called on the set time, it will change.

for example: If time is 10:00am and I set the alarm to be called in 20 minutes from now, then it will be called 10:20am. However if I go to settings and change system time to 9:00am after setting the alarm, then my app will be called from 100minutes from now. How do i prevent this, so that when the time for alarm is set, and whatever the system time is, the alarm will be called after those minutes.

here is my code:

public void newSetAlarm(View view) {


        timeEntered = Integer.parseInt(editTextForTime.getText().toString());
        Intent AlarmIntent = new Intent(this, Alarm.class);
        AlarmIntent.putExtra(TIME_LEFT, timeEntered);
        pendingIntentForAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, AlarmIntent, 0);
        amAlarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        amAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeEntered * 60000, pendingIntentForAlarm);}

managed to solve this issue with

<receiver android:name=".TimeChangeBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET"/>
<action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>

in the manifest file and then create that class

 public class TimeChangeBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
DoWhatEverYouWantHere();

}}

The issue now is that, whenever I change the time in the setting, this broadcastreceiver gets called. But I only want it to be called when my alarm is running, and the user heads over to setting to change time. When there is no alarm, and the user changes time in settings, I don't want the broadcastreceiver to be run in the background.

How do I solve that


Solution

  • Instead of using RTC_WAKEUP when setting the alarm, use ELAPSED_REALTIME_WAKEUP instead. Make sure that you provide the delta between NOW and the time you want the alarm to trigger as the "trigger" time instead of the clock time.

    Elapsed realtime measures time since the device was booted. It does NOT change when the device's clock is changed. If you do it this way you do not need to deal with clock or timezone changes.

    Read https://developer.android.com/reference/android/os/SystemClock for detailed information about the different clocks you can use and which one you should use for which scenario.