Sobes.tech
Middle

What is a PendingIntent?

sobes.tech AI

Answer from AI

PendingIntent is a token that allows another application to perform a part of your application's code on your behalf with your permissions.

It is used for:

  • Notifications (launching an activity when clicking on a notification).
  • Desktop widgets (handling user clicks).
  • Scheduler services (repeating tasks with AlarmManager).

Main differences from a regular Intent:

  • PendingIntent is passed to another application.
  • PendingIntent retains the permissions of the original application.

Types of PendingIntent:

  • getActivity(): To launch an Activity.
    // Creating a PendingIntent to launch an Activity
    val intent = Intent(context, TargetActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
    
  • getService(): To launch a Service.
    // Creating a PendingIntent to launch a Service
    val intent = Intent(context, MyService::class.java)
    val pendingIntent = PendingIntent.getService(context, 0, intent, 0)
    
  • getBroadcast(): To send a broadcast message.
    // Creating a PendingIntent to send a Broadcast
    val intent = Intent("MY_ACTION")
    val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
    

Flags of PendingIntent affect behavior:

Flag Description
FLAG_ONE_SHOT PendingIntent can be used only once.
FLAG_NO_CREATE If the PendingIntent does not exist, do not create it, return null.
FLAG_CANCEL_CURRENT If a PendingIntent with the same Intent already exists, cancel it and create a new one.
FLAG_UPDATE_CURRENT If a PendingIntent with the same Intent already exists, update its extras.
FLAG_IMMUTABLE PendingIntent cannot be modified by other applications (recommended).

When using PendingIntent, it is important to specify unique request codes (the second argument in the methods getActivity, getService, getBroadcast) to distinguish them.

What is a PendingIntent? — Android - sobes.tech