Metro Smurf
Metro Smurf

Reputation: 38335

Android: Start Service with Context.startService vs 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();


Questions

  1. When would you start a service with Context.startService vs a PendingIntent?
  2. Why would you use one over the other?

Upvotes: 17

Views: 13294

Answers (2)

Sobakus
Sobakus

Reputation: 181

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:

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

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.

Upvotes: 1

jtt
jtt

Reputation: 13541

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.

Upvotes: 19

Related Questions