Android: How to use AlarmManager

前端 未结 6 1073
时光取名叫无心
时光取名叫无心 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:23

    An AlarmManager is used to trigger some code at a specific time.

    To start an Alarm Manager you need to first get the instance from the System. Then pass the PendingIntent which would get executed at a future time that you specify

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
    Intent alarmIntent = new Intent(context, MyAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    int interval = 8000; //repeat interval
    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
    

    You need to be careful while using the Alarm Manager. Normally, an alarm manager cannot repeat before a minute. Also in low power mode, the duration can increase to up to 15 minutes.

提交回复
热议问题