0

I 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?

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

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

As you can see, I'm not sure how to use the alarmMgr.set function correctly. Also, do I need to run it as a service, so if the application will be exited, then it'll still work ?

Thanks!

Amit
  • 683
  • 3
  • 12
  • 25

1 Answers1

2

I saw you pass an Intent to the alarm manager

You pass a PendingIntent to AlarmManager.

are there other ways to do that?

The only way you can use AlarmManager is with a PendingIntent. The purpose of AlarmManager is to give your app control at points in time in the future when your app is no longer running.

Also, do I need to run it as a service, so if the application will be exited, then it'll still work ?

No. The goal of AlarmManager specifically is to allow your process to be terminated, yet give you control again some time in the future, so you are not tying up memory all that time.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you very much for the explaniation, but, How do I use it? if I want to run a specific function when the alarm goes off, how can I do it ? – Amit Nov 30 '13 at 17:12
  • If you're looking for an example which demostrates usage of `AlarmManager` take a look on this: http://stackoverflow.com/questions/4459058/alarm-manager-example – XorOrNor Nov 30 '13 at 17:16
  • @Amit: You do not "run a specific function when the alarm goes off". You either start an activity, send a command to a service, or send a broadcast. You need to choose which of those three options is what you want, then set up a `PendingIntent` for that operation. Where your code from `foo()` goes depends upon which of those three options you chose and other characteristics, such as whether you are using a `_WAKEUP`-style alarm. Using `AlarmManager` properly is rather complex (my book's chapter on it is ~30 pages) and beyond the scope of a single StackOverflow answer. – CommonsWare Nov 30 '13 at 17:18
  • Thanks for the help guys! but I've edited my code to something similar to the examples, yet it does not work... Please check my main post, I have edited there. @CommonsWare Thanks! – Amit Nov 30 '13 at 17:28
  • 1
    You have already got the extensive answer for your question. For another question please open another topic. – XorOrNor Nov 30 '13 at 17:31