13

Context.startService安卓:启动服务与Context.startService VS PendingIntent.getService

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. 为什么你会用另一个呢?

回答

18

确实没有区别。

具体来说,上下文方法用于直接启动它,因为PendingIntent通常与通知一起使用,以便在用户点击该对象时激发此意图,这会延迟到用户点击它(通常为止)。然而;你通常不会直接发送PendingIntent,因为这不是它的目的。

PendingIntent是一个意图挂起,挂起,这意味着它的不是现在应该发生,但在不久的将来。而用意图,它是在当下发送的。

如果PendingIntent在使用时没有挂起,那么它不再是PendingIntent,它实际上是一个Intent。 完全击败目的

+0

那么,你有没有想过用PendingIntent启动服务? – 2012-02-07 23:19:18

+2

如果您想在不久的将来启动服务,这将是理想的情况。假设我有一个通知,显示用户帐户可用的新更新。理想情况下,会有一个挂起的意图,建立连接到服务器并下载此信息。我希望在用户点击通知后立即完成,这样我就等待用户的方便,或者如果用户不关心他们可以取消通知,并且下一个新更新将以同样的方式作出反应。 – JoxTraex 2012-02-08 00:01:10

+0

很好的解释,谢谢! – damluar 2014-06-02 11:22:11

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()中加入额外的信息,这样服务将获得任何需要的信息来完成它的工作。

+0

只需注意您必须在清单 中添加您的服务并添加export =“true”属性其重要 – Lior 2017-12-28 21:57:39