简体   繁体   中英

How to run a function when Alarm Manager finishes?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM