Search code examples
javaandroidalarmmanager

AlarmManager doesnt work


want to run the function foo() when the alarm manager runs off, but I have not understood how do I do it. I saw you pass an Intent to the alarm manager, are there other ways to do that?

Here is my code :

public void onReceive(Context context, Intent intent) 
{   
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
   wl.acquire();

   Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
   Log.e(TAG, "ALARM!");
   wl.release();
   }

 public void SetAlarm()
 {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.set(Calendar.MINUTE, 27);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

 AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, TaskOpt.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}

This code doesnt work to me, as It does not get onto onRecive... what have I done wrong?

Thanks!


Solution

  • First, your onReceive() needs to be in a class, named TaskOpt, that is a BroadcastReceiver and is registered as such in the manifest.

    Second, if it is after 19:27 local time, your Calendar object is in the past. You need to check for this and add a day if necessary. You can use adb shell dumpsys alarm to find out what alarms are scheduled.

    Third, I would recommend using WakefulBroadcastReceiver, or my WakefulIntentService, rather than using a WakeLock directly. Getting WakeLocks right is tricky, and you are better served using established patterns, implemented in existing libraries.

    Beyond that, examine LogCat and see if there are any messages, and ensure that your SetAlarm() method is actually getting called.