androidservicealarmmanageralarms

AlarmManager Elapsed Real time Not Working?


So I am new to the elapsed realtime alarm, and I tried to make my service run after the phone was turned on, but the service doesn't seem to get run.

Setting Alarm.

Intent sintent=new Intent(getApplicationContext(),alrmsetter.class);
        PendingIntent setter= PendingIntent.getService(getApplicationContext(),137,sintent,0);
        AlarmManager mmanager=(AlarmManager)getSystemService(ALARM_SERVICE);
        mmanager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,6*1000,setter);

Service

public class alrmsetter extends Service
{
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    public int onStartCommand(Intent intent, int flags, int startId)
    {
       Log.i("AREW","CLASS STRTED?");
        return super.onStartCommand(intent, flags, startId);

    }
}

Solution

  • I tried to make my service run after the phone was turned on, but the service doesn't seem to get run

    Alarms do not persist through reboots, so regardless of whether you set the alarm before the phone was shut down, the alarm will not trigger on the next boot unless it is set again.

    This is effectively what the BOOT_COMPLETED broadcast intent action is for. It gives applications the ability to set (or reset) their alarms on startup. This dev guide talks about how to use it. If you are targeting Android 5.0+, you can often use JobScheduler to trigger a service in a similar way and it will persist the work for you.

    In your case, you are trying to set an alarm for "6 seconds after the device boots". This may be tricky as the elapsed realtime clock starts from the low-level boot stages, and by the time even BOOT_COMPLETED fires, it will have been more than 6 seconds on most devices.

    If you truly need to do something at boot time, handle it directly in the BOOT_COMPLETED receiver handler (i.e. start your service there). Then use an alarm if you need to repeat the action after that point.