【问题标题】:Android: Start Service with Context.startService vs PendingIntent.getServiceAndroid:使用 Context.startService 与 PendingIntent.getService 启动服务
【发布时间】:2012-02-27 12:05:20
【问题描述】:

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. 为什么要使用一个而不是另一个?

【问题讨论】:

    标签: android android-intent android-context android-pendingintent


    【解决方案1】:

    真的没有区别。

    特别是 Context 方法用于直接启动它,因为 PendingIntent 通常与通知一起使用,以在点击它时触发此意图,这会延迟到用户点击它(通常)。然而;您通常不会直接发送 PendingIntent,因为这不是它的用途。

    A PendingIntent 是一个待处理、待处理的 Intent,意味着它的应该现在发生,但在不久的将来。而对于 Intent,它是在当下发送的。

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

    【讨论】:

    • 那么,您是否曾经想要使用 PendingIntent 启动服务?
    • 如果您想在不久的将来启动服务,这将是理想的情况。假设我有一个通知,显示用户帐户可用的新更新。理想情况下,会有一个挂起的意图来建立与服务器的连接并下载此信息。我希望在用户没有立即点击通知时完成它,这样我等待用户的方便,或者如果用户不关心他们可以取消通知,下一个新的更新将以相同的方式做出反应。
    【解决方案2】:

    PendinIntent 非常多地用于小部件。由于正在运行的小部件的布局不“属于”您的代码,而是在系统的控制之下,因此您不能直接将点击侦听器分配给界面元素。相反,您将 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() 在 Intent 中添加额外信息,因此服务将获得完成其工作所需的任何信息。

    【讨论】:

    • 请注意,您必须在清单中添加您的服务并添加 export="true" 属性其重要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多