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!
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.