Android:使用 Context.startService 与 PendingIntent.getService 启动服务
Context.startService
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
PendingIntent.getService
Intent intent = new Intent(context, MyService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
pi.send();
问题
- 您何时会使用 Context.startService 与 PendingIntent 启动服务?
- 为什么你会使用其中一种而不是另一种?
Context.startService
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
PendingIntent.getService
Intent intent = new Intent(context, MyService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
pi.send();
Questions
- When would you start a service with Context.startService vs a PendingIntent?
- Why would you use one over the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实没有什么区别。
具体来说,Context 方法用于直接启动它,而 PendingIntent 通常与通知一起使用,以便在点击它时触发此意图,该通知会延迟到用户点击它(通常)。然而;您通常不会直接发送 PendingIntent,因为这不是它的用途。
PendingIntent 是一个待处理的 Intent,这意味着它不应该在现在发生,而是在不久的将来发生。而对于 Intent,它是在此时发送的。
如果 PendingIntent 在使用时不是挂起的,那么它就不再是 PendingIntent,而实际上是一个 Intent。 完全违背了目的。
There really is no difference.
Specifically the Context method is used to directly start it where as a PendingIntent is typically used with a notification to fire this intent when it is tapped, which is delayed until the user taps it (typically). However; you wouldn't typically send the PendingIntent directly because that is not what it is for.
A PendingIntent is an Intent that is pending, pending, meaning that its NOT supposed to happen now, but in the near future. Whereas with an Intent, it is sent at the very moment.
If a PendingIntent is not pending when it is used, then it is no longer a PendingIntent and it is infact an Intent. Defeating the purpose entirely.
PendinIntents 广泛用于小部件。由于正在运行的小部件的布局并不“属于”您的代码,而是受系统控制,因此您无法将单击侦听器直接分配给界面元素。相反,您将 PendingIntent 分配给这些元素(如按钮),以便当用户触摸它们时,PendingIntent 被“执行”,类似于:
在本例中,小部件中的按钮启动服务。通常,您可以使用 putExtras() 在意图中添加额外的信息,以便服务将获得完成其工作所需的任何信息。
PendinIntents are very much used for widgets. As the layout of a running widget doesn't "belong" to your code, but it is instead under control of the system, you can't assign directly click listeners to the interface elements. Instead you assign a PendingIntent to those elements (like buttons) so when the user touches them, the PendingIntent is "executed", something like:
In this case a button in the widget starts a service. Usually you put extra info in the intent, with putExtras(), so the service will get any needed information to do its job.