main

square/leakcanary

Last updated at: 29/12/2023 09:39

NotificationReceiver.kt

TLDR

The NotificationReceiver.kt file is a part of the LeakCanary library and contains the NotificationReceiver class, which extends the BroadcastReceiver class. The NotificationReceiver class is responsible for receiving broadcast intents and performing actions based on the specified action.

Methods

onReceive

This method is invoked when a broadcast intent is received. It determines the action specified in the intent and performs the corresponding operation. If the action is DUMP_HEAP, it calls the onDumpHeapReceived method of the InternalLeakCanary class with forceDump set to false. If the action is CANCEL_NOTIFICATION, it does nothing. If the action is unknown, it logs a debug message.

pendingIntent

This method creates a pending intent with the specified action. It is used to create a pending intent for the NotificationReceiver class. The method creates an intent with the specified action and returns a pending intent with that intent.

Classes

NotificationReceiver

This class extends the BroadcastReceiver class and is responsible for receiving broadcast intents and performing actions based on the specified action. It contains the onReceive method and the pendingIntent method.

package leakcanary.internal

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import leakcanary.internal.NotificationReceiver.Action.CANCEL_NOTIFICATION
import leakcanary.internal.NotificationReceiver.Action.DUMP_HEAP
import shark.SharkLog

internal class NotificationReceiver : BroadcastReceiver() {

  enum class Action {
    DUMP_HEAP,
    CANCEL_NOTIFICATION
  }

  override fun onReceive(
    context: Context,
    intent: Intent
  ) {
    when (intent.action) {
      DUMP_HEAP.name -> {
        InternalLeakCanary.onDumpHeapReceived(forceDump = false)
      }
      CANCEL_NOTIFICATION.name -> {
        // Do nothing, the notification has auto cancel true.
      }
      else -> {
        SharkLog.d { "NotificationReceiver received unknown intent action for $intent" }
      }
    }
  }

  companion object {
    fun pendingIntent(
      context: Context,
      action: Action
    ): PendingIntent {
      val broadcastIntent = Intent(context, NotificationReceiver::class.java)
      broadcastIntent.action = action.name
      val flags = if (Build.VERSION.SDK_INT >= 23) {
        PendingIntent.FLAG_IMMUTABLE
      } else {
        0
      }
      return PendingIntent.getBroadcast(context, 0, broadcastIntent, flags)
    }
  }
}