Android AlarmManager广播接收器和服务

本文详细介绍了如何在Android应用中使用AlarmManager和BroadcastReceiver来触发后台服务。AlarmManager允许在特定时间独立于应用生命周期执行代码,有不同类型的触发方式。BroadcastReceiver监听系统和应用事件,当系统重启时可通过设置ACTION_BOOT_COMPLETED来触发。文中还展示了项目结构、代码实现,包括MainActivity、BroadcastReceiver和服务的启动,以及应用运行的输出结果。
摘要由CSDN通过智能技术生成

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值