title: How to start an alarm if the mobile is switch off
body: <p>In my app, I use the <code>AlarmManager</code> class to set an alarm. To trigger the alarm after the mobile is rebooted I have used <code>BroadcastReceiver</code>. All works fine and my alarm is triggered at regular intervals. Now the problem arises in this case :</p>
  <p>Suppose my current time is <strong>2:30 pm</strong> and I set my alarm at <strong>2:35 pm</strong>. After that, I switch off the mobile. After an hour when I switch on my mobile, no alarm is pop-up as the time on which the alarm is set. This is happening because the current time exceeds the time on which I set the alarm. To solve this issue what should I do. I have posted my code for setting alarm in the <code>AlarmManager</code> class. Please help me to solve this out</p>
  <pre><code>public class AlarmReceiver extends BroadcastReceiver {
      @SuppressWarnings(&quot;static-access&quot;)
      @Override
      public void onReceive(Context context, Intent intent) {
          if(intent.getAction().equals(&quot;android.intent.action.BOOT_COMPLETED&quot;)) {
              Intent myIntent = new Intent(context, MyAlarmService.class); 
              PendingIntent pendingIntent = PendingIntent.getService(context, i, myIntent, i);                            
              AlarmManager alarmManager = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
              Calendar calendar = Calendar.getInstance(); 
              calendar.setTimeInMillis(System.currentTimeMillis()); 
              calendar.add(Calendar.MILLISECOND, (int) Utilities.diff(NoteManager.getSingletonObject().getAlarmTime(i)));                 
              alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
          }
      }
  }
  
  public static long diff(Date date) {
      long difference = 0;
      try {
          // set current time
          Calendar c = Calendar.getInstance();
          difference = date.getTime() - c.getTimeInMillis();
          if (difference &lt; 0) {
              // if difference is -1 - means alarm time is of previous time then current
              // then firstly change it to +positive and subtract form 86400000 to get exact new time to play alarm
              // 86400000-Total no of milliseconds of 24hr Day
              difference = difference * -1;
              difference = 86400000 - difference; 
          }
      } 
      catch (Exception e) {
          e.printStackTrace();
      }
      return difference;
  }
  </code></pre>
  <p><strong>In The Manifest File</strong></p>
  <pre><code>&lt;receiver android:name=&quot;.AlarmReciever&quot;&gt;
      &lt;intent-filter&gt;
          &lt;action android:name=&quot;android.intent.action.BOOT_COMPLETED&quot; /&gt;
      &lt;/intent-filter&gt;
  &lt;/receiver&gt;
  &lt;uses-permission android:name=&quot;android.permission.RECEIVE_BOOT_COMPLETED&quot; /&gt;
  </code></pre>