Can’t start activity from BroadcastReceiver on android 10

Android 10’s restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.

Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:

val pi = PendingIntent.getActivity(
  appContext,
  0,
  Intent(appContext, MainActivity::class.java),
  PendingIntent.FLAG_UPDATE_CURRENT
)

val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
  .setSmallIcon(R.drawable.ic_notification)
  .setContentTitle("Um, hi!")
  .setAutoCancel(true)
  .setPriority(NotificationCompat.PRIORITY_HIGH)
  .setFullScreenIntent(pi, true)

val mgr = appContext.getSystemService(NotificationManager::class.java)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
  && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
  mgr.createNotificationChannel(
    NotificationChannel(
      CHANNEL_WHATEVER,
      "Whatever",
      NotificationManager.IMPORTANCE_HIGH
    )
  )
}

mgr.notify(NOTIF_ID, builder.build())

Leave a Comment