Notifications & Permissions

Android Development with Compose: Production & Publishing

Course 6 ยท Chapter 4 ยท Asking Before You Interrupt

A notification interrupts someone, so Android makes you ask first. This chapter adds a reminder to a note: it creates a notification channel, asks for the notification permission in Compose, copes with a "no", and uses Android Development with Compose: Production & Publishing 3's WorkManager to fire the reminder later.

What was checked, and how: read this first
Checked in the docs (two searches, summaries only): Permission: Android 13 (API 33) added POST_NOTIFICATIONS as a runtime permission, applying to all apps running on Android 13 whatever their target; if denied, the app cannot send notifications unless it has an exemption; newly installed apps start with notifications off, while upgraded apps are typically pre-granted; before sending, call areNotificationsEnabled(); notify is annotated as requiring the permission. Channels: required on Android 8.0+; create them when the app starts, since creating an existing one does nothing; create before posting. Compose request: rememberLauncherForActivityResult with ActivityResultContracts.RequestPermission(), launching the permission behind a check for Android 13; no rationale screen is needed unless shouldShowRequestPermissionRationale() returns true; in Compose the current Activity can be taken from LocalContext.current. Exact alarms: SCHEDULE_EXACT_ALARM is a special access permission, user-revocable, for user-facing features; USE_EXACT_ALARM is for apps whose core function is alarms, timers or calendars; since Android 14 the first is denied by default for most new apps targeting Android 13+; call canScheduleExactAlarms() and otherwise send the user to ACTION_REQUEST_SCHEDULE_EXACT_ALARM. Not found (general knowledge, not checked): the PendingIntent and deep-link code, the notification builder as written, the settings intent, the small icon resource, Accompanist's permissions library (not searched), and the interplay with Chapter 3's foreground-service notifications. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

Channels

<!-- AndroidManifest.xml: declare the permission (Android 13+ asks the user at run time) --> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context const val REMINDER_CHANNEL_ID = "note_reminders" fun createNotificationChannels(context: Context) { // Channels exist on Android 8.0+ (API 26); minSdk 26 or higher needs no version check val channel = NotificationChannel( REMINDER_CHANNEL_ID, "Note reminders", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "Reminders you set on a note" } context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel) } // In NotesApplication.onCreate(): createNotificationChannels(this) // (docs: create the channel at app start; creating an existing channel does nothing)
  • (docs) Channels are required from Android 8.0. Create them at app start; making one that already exists does nothing.
  • (general knowledge) The channel carries the user-visible name and the importance. After it is created, you cannot change the user's choices: they control sound and importance in system settings. Choose the importance carefully, and use one channel per kind of notification so users can silence reminders without silencing everything.

Posting a Notification

import android.Manifest import android.app.PendingIntent import android.content.Intent import android.content.pm.PackageManager import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat fun showReminder(context: Context, noteId: Long, text: String) { val openApp = PendingIntent.getActivity( context, noteId.toInt(), Intent(context, MainActivity::class.java).putExtra("noteId", noteId), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) val notification = NotificationCompat.Builder(context, REMINDER_CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_note) .setContentTitle("Note reminder") .setContentText(text) .setContentIntent(openApp) .setAutoCancel(true) .build() // notify() is annotated as needing POST_NOTIFICATIONS (docs), so check first val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED if (allowed) { NotificationManagerCompat.from(context).notify(noteId.toInt(), notification) } }
  • (docs) notify needs POST_NOTIFICATIONS on Android 13+, so the code checks first. (docs) areNotificationsEnabled() is the other check the guide mentions.
  • (general knowledge) The PendingIntent says what happens on a tap. FLAG_IMMUTABLE is the safe default on current Android; the extra noteId lets MainActivity open that note. A different request code per note stops reminders from overwriting each other's intents.
  • (general knowledge) A notification needs a small icon (ic_stat_note here is a drawable you supply) or it will not appear properly.

Asking for the Permission in Compose

import android.Manifest import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.* @Composable fun NotificationPermissionButton(onResult: (Boolean) -> Unit) { val launcher = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), onResult // true if the user allowed it ) Button(onClick = { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) } else { onResult(true) // before Android 13 there is nothing to ask } }) { Text("Allow reminders") } }
  • (docs) The sample uses exactly this launcher with RequestPermission(), behind an Android 13 version check.
  • When to ask. (general knowledge) At the moment the user taps "Remind me", not at app start, because then they know why. A system dialog without context is easy to refuse.
  • Rationale. (docs) You do not need to show a rationale screen unless shouldShowRequestPermissionRationale() returns true; the method needs the Activity, available through LocalContext.current.

When the User Says No

import android.content.Intent import android.net.Uri import android.provider.Settings // Ask at the moment the user wants a reminder, not at app start. // If they said no, explain and offer the system settings page instead of asking again. fun openNotificationSettings(context: Context) { val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) context.startActivity(intent) }

(docs) A denial means no notifications. (general knowledge, not checked) After repeated denials the system may stop showing the dialog, so asking again does nothing. The respectful design is: the app keeps working (the reminder is simply not set), explain once why it would help, and offer a button to the system settings page. Never nag, and never make a core feature depend on the permission.

The Reminder, Built on WorkManager

class ReminderWorker( appContext: Context, params: WorkerParameters ) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result { val id = inputData.getLong("noteId", -1) val text = inputData.getString("text") ?: return Result.failure() showReminder(applicationContext, id, text) return Result.success() } } // "Remind me in an hour": inexact, so no exact-alarm permission is needed fun scheduleReminder(context: Context, noteId: Long, text: String, delayMinutes: Long) { val request = OneTimeWorkRequestBuilder<ReminderWorker>() .setInitialDelay(delayMinutes, TimeUnit.MINUTES) .setInputData(workDataOf("noteId" to noteId, "text" to text)) .build() WorkManager.getInstance(context).enqueueUniqueWork( "reminder-$noteId", ExistingWorkPolicy.REPLACE, request ) }
  • (docs, Chapter 3) setInitialDelay delays a one-time request; unique work with REPLACE means setting a new reminder for the same note replaces the old one.
  • (general knowledge) This is inexact: the system may run it a little late to save battery, which is fine for "remind me in an hour".

Exact Alarms (described, not used)

// Only if a feature truly needs an exact time (the docs say: user-facing features) val alarmManager = context.getSystemService(AlarmManager::class.java) if (alarmManager.canScheduleExactAlarms()) { // schedule the exact alarm } else { context.startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM)) }
  • (docs) Exact timing needs SCHEDULE_EXACT_ALARM (user-revocable, for user-facing features) or USE_EXACT_ALARM (only for apps whose core function is alarms, timers or calendars).
  • (docs) Since Android 14 the first is denied by default for most new apps targeting Android 13+, so you must check canScheduleExactAlarms() and, if false, send the user to the settings screen.
  • (general knowledge) A notes app's "remind me later" does not need to the second, so it should not request exact alarms: asking for a permission you do not need costs trust, and Google Play reviews such requests (checked for real in Chapter 7).

Permissions in General

KindHow the user grants itExample here
Normal (install time)Granted automaticallyINTERNET (general knowledge)
RuntimeA system dialog, at the moment you askPOST_NOTIFICATIONS (docs)
Special accessA settings screen you send them toSCHEDULE_EXACT_ALARM (docs)
Compared with the Classic UI course
Android Development: Production & Publishing 4 teaches notifications and permissions. The notification code is the same (it does not depend on Compose); the Compose edition requests permission with rememberLauncherForActivityResult instead of the Activity's callbacks, and builds the reminder on WorkManager.

Try It Yourself

Exercise 1

Add the manifest permission, the channel and showReminder, with a debug button that posts one immediately. Test on Android 13+ and on an older emulator if you have one. Report what happens before and after granting, and where the channel appears in system settings.

๐Ÿ“„ View solution
Exercise 2

Build the permission flow: tapping "Remind me" asks once, and a denial shows a message with a button to the settings page. Deny twice and report what the system does the third time.

๐Ÿ“„ View solution
Exercise 3

Add ReminderWorker and scheduleReminder, set a reminder for one minute ahead, and tap the notification. Make MainActivity read noteId and open that note. Say why you would not use an exact alarm here.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (two searches, summaries only): the Android 13 runtime permission and its all-apps scope; denial blocking notifications; new against upgraded installs; areNotificationsEnabled(); the notify annotation; channels on Android 8.0+ and creating them at start; the Compose launcher sample and version check; rationale and LocalContext.current; the exact-alarm permissions, the Android 14 default and canScheduleExactAlarms().
General knowledge, not checked: the notification builder, PendingIntent flags and the deep-link extra; the small icon requirement; the channel choices being the user's afterwards; the settings intent; the system stopping the dialog after repeated denials; the worker and its inexact timing; the permission-kinds table's install-time row; the Play review remark; every import and the code as written.
Not verified: Accompanist's permissions library (not searched); foreground-service notification rules (the second search did not return them); every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Notification runtime permission (developer.android.com), Create a notification, Compose (developer.android.com), Display time-sensitive notifications (developer.android.com), Behavior changes: all apps, Android 13 (developer.android.com), Schedule exact alarms are denied by default (developer.android.com), Schedule alarms (developer.android.com).
Coming up
Chapter 5 is App Security: shrinking and obfuscating with R8, secure storage, biometric sign-in, network security, and keeping secrets out of the code.