Android: How to use AlarmManager

前端 未结 6 1074
时光取名叫无心
时光取名叫无心 2020-11-22 06:40

I need to trigger a block of code after 20 minutes from the AlarmManager being set.

Can someone show me sample code on how to use an AlarmManager<

6条回答
  •  耶瑟儿~
    2020-11-22 07:21

    "Some sample code" is not that easy when it comes to AlarmManager.

    Here is a snippet showing the setup of AlarmManager:

    AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(context, OnAlarmReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
    
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
    

    In this example, I am using setRepeating(). If you want a one-shot alarm, you would just use set(). Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to set(). In my example above, I am using AlarmManager.ELAPSED_REALTIME_WAKEUP, so my time base is SystemClock.elapsedRealtime().

    Here is a larger sample project showing this technique.

提交回复
热议问题