我应该在AlarmManager中使用PendingIntent.getService()或getBroadcast吗? [英] Should I use PendingIntent.getService() or getBroadcast with AlarmManager?

查看:880
本文介绍了我应该在AlarmManager中使用PendingIntent.getService()或getBroadcast吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用每天需要在特定时间从网络上获取一些数据。因此,我使用AlarmManager来安排任务,并且可以正常工作。

My app needs to grab some data from the web at a specific time each day. So I use an AlarmManager to schedule the task and that works ok.

但是在查看各种示例时,似乎有两种方法可以处理AlarmManager。

But when looking at various examples there seems to be two ways to deal with the AlarmManager when it comes to the pending intent.

一个在警报响起时使用 PendingIntent.getBroadcast()呼叫广播接收器,并且

One uses PendingIntent.getBroadcast() to call a broadcast receiver when the alarm goes off and inside that receiver the service to do the real work is started.

另一种方法是使用 PendingIntent.getService(),然后在警报响起时直接致电服务。

Another approach is to use PendingIntent.getService() and call the service directly when that alarm goes off.

有人可以向我解释两种方法之间的区别,以便我可以确定要依靠哪种方法吗?

Can someone explain to me the difference between the two approaches so I can decide on which one to rely?

编辑:另一个问题是使用getService()时在哪里获取唤醒锁?

例如,当使用BroadcastReceiver时,我在onReceive()中包含以下行:

For example, when using a BroadcastReceiver I have the following line in onReceive():

WakeReminderIntentService.acquireStaticLock(context);

如果我直接调用该服务,例如:

How should I acquire the wake lock if I instead call the service directly like:

PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, OnAlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);

我应该只是从服务内获取它吗?

Should I simply acquire it from within the service instead?

推荐答案

一个使用 PendingIntent.getBroadcast()调用广播接收器当警报响起并在接收器内部启动服务时,开始执行真正的工作。

One uses PendingIntent.getBroadcast() to call a broadcast receiver when the alarm goes off and inside that receiver the service to do the real work is started.

启动服务的步骤比

另一种方法是使用 PendingIntent.getService()并在警报响起时直接调用服务。

Another approach is to use PendingIntent.getService() and call the service directly when that alarm goes off.

然后您应该使用第二种方法,因为它减少了执行的第一步。

then you should use the second approach as it is reducing your one step in execution..

这篇关于我应该在AlarmManager中使用PendingIntent.getService()或getBroadcast吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆