In this tutorial, we’ll be discussing AlarmManager and Broadcast Receiver and see how to trigger a Background Service using them in our Android Application.
在本教程中,我们将讨论AlarmManager和Broadcast Receiver,并了解如何在我们的Android应用程序中使用它们触发后台服务。
AlarmManager广播接收器服务 (AlarmManager Broadcast Receiver Service)
An AlarmManager is used to trigger some code at a specific time. It uses the Android SDK’s alarm service and runs independently of the application’s lifecycle.
AlarmManager用于在特定时间触发一些代码。 它使用Android SDK的警报服务,并且独立于应用程序的生命周期运行。
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.
要启动警报管理器,您需要首先从系统获取实例。 然后传递PendingIntent,它将在您指定的将来时间执行。
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;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
There are different types of Alarm Manager that can be invoked:
可以调用不同类型的警报管理器:
setInExactAndRepeating
– This doesn’t trigger the alarm at the exact time.setInExactAndRepeating
–这不会在确切时间触发警报。setExact
– Setting an alarm manager using this ensures that the OS triggers the alarm at almost the exact time.setExact
–使用此设置警报管理器可确保操作系统几乎在准确的时间触发警报。setExactAndAllowWhileIdle
– This method came up with Android M. These types of alarms are allowed to get executed even in low power modes.setExactAndAllowWhileIdle
– Android M附带了此方法。即使在低功耗模式下,也可以执行这些类型的警报。
You need to be careful while using the Alarm Manager since they can consume battery if not handled properly.
Normally, an alarm manager cannot repeat before a minute. Also in low power mode, the duration can increase to up to 15 minutes.
使用警报管理器时需要小心,因为如果处理不当,它们可能会消耗电池。
通常,警报管理器不会在一分钟前重复。 同样在低功耗模式下,持续时间最多可以增加15分钟。
Broadcast Receivers li