Sobes.tech
Middle

What is a PendingIntent?

sobes.tech AI

Answer from AI

This is a wrapper around Intent that delegates authority to another application to perform this Intent on our behalf in the future.

Key features:

  • Deferred execution: Intent is executed later by another component.
  • Permissions: The component receiving the PendingIntent gets the same permissions as our application to execute this Intent.
  • Uniqueness: Different PendingIntents are considered the same if they match in component type, action, data, categories, and flags.
  • Usage: Commonly used for notifications, background tasks, widgets, and AlarmManager.

The types of PendingIntent correspond to the types of target components:

  • getActivity(Context context, int requestCode, Intent intent, int flags): launches an Activity.
  • getBroadcast(Context context, int requestCode, Intent intent, int flags): sends a broadcast.
  • getService(Context context, int requestCode, Intent intent, int flags): starts or binds to a Service.
  • getForegroundService(Context context, int requestCode, Intent intent, int flags): starts a Foreground Service.
// Example of creating a PendingIntent for Notifications
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
    context,
    0, // requestCode, used to distinguish PendingIntents
    notificationIntent,
    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE // Flags to control behavior
);
// Now this pendingIntent can be passed, for example, to a Notification

Flags (flags) influence behavior when creating or updating an existing PendingIntent:

  • FLAG_ONE_SHOT: PendingIntent can only be used once.
  • FLAG_NO_CREATE: If the PendingIntent does not exist, it is not created, and null is returned.
  • FLAG_CANCEL_CURRENT: If a PendingIntent with the same parameters already exists, it is canceled, and a new one is created.
  • FLAG_UPDATE_CURRENT: If a PendingIntent with the same parameters already exists, its additional data (Extra data) is updated.
  • FLAG_IMMUTABLE (starting from S/API 31, mandatory for most cases): Creates an immutable PendingIntent.
  • FLAG_MUTABLE: Creates a mutable PendingIntent (use with caution, may be vulnerable).

Choosing the correct flag is critical for proper operation and security.

What is a PendingIntent? — Android - sobes.tech