我应该将 PendingIntent.getService() 还是 getBroadcast 与 AlarmManager 一起使用? [英] Should I use PendingIntent.getService() or getBroadcast with AlarmManager?

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

问题描述

我的应用需要在每天的特定时间从网络获取一些数据.所以我使用了一个 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?

推荐答案

One 使用 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..

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

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