Search code examples
androidalarmmanagerandroid-alarms

Alarm not working in android?


I get stuck with something that , I guess , is very trivial. Basically I am scheduling alarm for a given moment in the future :

Intent contentIntent = new Intent(this, AlarmReceiver.class); 
PendingIntent theappIntent = PendingIntent.getService(Main.this, 0,contentIntent, 0); 
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, hour,minute); 
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), theappIntent); 

works fine while mobile is constantly on. My problem is that alarm is not triggered after mobile is restarted and is TURNED ON on the expected time. Is there something I missed? Should I do some extra work to keep alarm scheduled after restart?


Solution

  • You have to reset the alarm when device get boot. You are missing to detect the app when device boot and reset the alarm..so below is code written in manifest

    <receiver android:name=".YourReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
    </receiver>
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    

    Also create a BroadcastReceiver to receive the boot completed intent

     public class YourReceiver extends BroadcastReceiver {
    
    
     Context ct;
    
     @Override
     public void onReceive(Context context, Intent intent) 
     {
        ct=context;
        if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
        {
          // Reset your alarm here
          Intent contentIntent = new Intent(ct, AlarmReceiver.class); 
          PendingIntent theappIntent = PendingIntent.getService(ct, 0,contentIntent, 0); 
          Calendar calendar = Calendar.getInstance();
          calendar.set(year, month, day, hour,minute); 
          AlarmManager am = (AlarmManager) ct.getSystemService(ALARM_SERVICE);
          am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), theappIntent); 
        }
     }