Sobes.tech
Junior — Middle

What is the role of the PendingIntent object and in which scenarios is it used in Android application development?

sobes.tech AI

Answer from AI

The PendingIntent object in Android represents a deferred intent (Intent) that can be executed by another application or the system on behalf of your application in the future.

The role of PendingIntent is to provide an external component (such as NotificationManager, AlarmManager, AppWidgetManager) with the ability to perform a predefined action with your application's permissions.

Main use cases:

  • Notifications — for handling notification clicks.
  • AlarmManager — to run code at a specific time.
  • App Widgets — to handle interactions with widgets.
  • BroadcastReceiver — to send deferred broadcast messages.

Example of creating a PendingIntent for a notification:

val intent = Intent(context, TargetActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Title")
    .setContentText("Notification text")
    .setContentIntent(pendingIntent) // Tapping will open TargetActivity
    .build()