简体   繁体   English

Android警报管理器和待定意图

[英]Android Alarm Manager and Pending Intent

I am looking at the page for Alarm Manager in Android and see that we can use Pending Intent to trigger a component after a certain time using this feature. 我正在查看Android中“ 警报管理器”的页面,看到我们可以使用Pending Intent在一段时间后使用此功能来触发组件。

I can the see utility of this feature, but am interested in knowing why was this feature introduced. 我可以看到此功能的实用程序,但是对知道为什么引入此功能感兴趣。 Can't an application count time itself and trigger an Intent after a certain amount of time ? 应用程序不能自行计算时间并在一定时间后触发Intent吗? What are the unique advantages of using Pending Intent with Alarm Manager to achieve the same goal ? 将Pending Intent与Alarm Manager一起使用以实现相同目标的独特优势是什么?

Activities are volatile in Android. 活动在Android中不稳定。 Android can decide to destroy the application at any time or pause it. Android可以决定随时销毁该应用程序或暂停该应用程序。 If a long running activity is paused or destroyed, how can it know the current time and trigger the Intent? 如果长时间运行的活动被暂停或破坏,它如何知道当前时间并触发意图? Alarm Manager sets the alarm in the system and at that time, or roughly at the specified time, depending on the number of alarms set in the system the alarm is triggered, and you can use it to trigger an Intent. 警报管理器会在系统中以及当时或大致在指定时间设置警报,具体取决于系统中设置的警报数量,从而触发警报,您​​可以使用它来触发Intent。

Edit: an application can have a service. 编辑:应用程序可以提供服务。 The service is part of the application and runs on the application thread. 该服务是应用程序的一部分,并在应用程序线程上运行。 You can create an handler so it triggers some code from the current time to a determined number of seconds, and this is all fine, since the service won't continually run and take all the focus in the main thread. 您可以创建一个处理程序,以便从当前时间到确定的秒数触发一些代码,这一切都很好,因为该服务不会持续运行,并且不会将所有焦点都集中在主线程上。 A service is something that runs its code and then finishes. 服务是运行其代码然后完成的东西。 It doesn't stay there waiting on some line. 它不会在那儿排队等待。 It runs on the main thread so it can cause an ANR on the application if there is code in the service always running. 它在主线程上运行,因此如果服务中始终有代码在运行,则会在应用程序上引起ANR。 Counting time is not something that should be done, like a while loop in the service, because it takes all the processing power and freezes the application. 计数时间不是必须要做的事情,就像服务中的while循环一样,因为它会占用所有处理能力并冻结应用程序。 This is why an Alarm is useful, Android triggers it on that moment, it is not something that is processing in your application. 这就是警报有用的原因,Android会在那一刻触发它,而不是您的应用程序正在处理的东西。 Of course you can create a service in another thread, but unless counting time like a clock is really necessary, and I don't see why would it be, Alarm is better for this. 当然,您可以在另一个线程中创建服务,但是除非真的需要像时钟一样对时间进行计数,而且我不知道为什么会这样,否则Alarm对此会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM