Android: 使用Context.startService和PendingIntent.getService启动服务的区别

17

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();


问题

  1. 在什么情况下使用Context.startService而不是PendingIntent启动服务?
  2. 为什么会选择其中一个而不是另一个?
2个回答

19

实际上没有区别。

具体而言,Context方法是用于直接启动它,而PendingIntent通常与通知一起使用,在用户点击通知后触发该意图,这通常会被延迟到用户点击它时。但是,您通常不会直接发送PendingIntent,因为那不是它的用途。

PendingIntent是一个即将发生的Intent,即pending,表示它不应该立即发生,而是在不久的将来。而Intent则是立即发送的。

如果PendingIntent在使用时不再处于挂起状态,则它不再是PendingIntent,而实际上是一个Intent。完全打败了它的目的


那么,您是否曾经想过使用“PendingIntent”启动服务的时候? - Metro Smurf
2
如果您想在不久的将来启动一个服务,那么这是理想情况。假设我有一个通知显示用户帐户有新更新可用。理想情况下,应该有一个挂起的意图建立连接到服务器并下载这些信息。当用户点击通知时,我希望它完成,而不是立即执行,这样我可以等待用户方便,或者如果用户不关心,他们可以取消通知,并且下一个新的更新将以同样的方式响应。 - JoxTraex

1
PendinIntents 在小部件中被广泛使用。由于正在运行的小部件的布局不属于您的代码,而是在系统控制下,因此您无法直接为界面元素分配单击侦听器。相反,您将 PendingIntent 分配给这些元素(如按钮),因此当用户触摸它们时,PendingIntent 就会“执行”,类似于以下内容:
// get the widget layout
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.id.widget_layout);

// prepare to listen the clicks on the refresh button
Intent active = new Intent(context, WidgetCode.UpdateService.class);
PendingIntent refreshPendingIntent = PendingIntent.getService(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.buttonWidgetRefresh, refreshPendingIntent);

// send the changes to the widget
AppWidgetManager.getInstance(context).updateAppWidget(appwidgetid, remoteViews);

在这种情况下,小部件中的一个按钮会启动一个服务。通常您可以使用putExtras()在意图中添加额外的信息,以便服务能够获取执行其工作所需的任何信息。

1
请注意,在清单文件中添加您的服务,并添加export="true"属性,这非常重要。 - Lior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接