Exploring Android 13: Notification Runtime Permission
By this new change, your user has to grant this permission first before your app can post any notification. Also you as a developer can control when the permission dialog is displayed (Before Android 13, the permission dialog is displayed by the system when you create your first notification channel).
In this article, we will create a simple application that uses this new notification permission. Here’s what it will look like in the end:
Where’s the Source Code?
android-13-samples/notification-runtime-permission at master · hanmajid/android-13-samples
Sample projects for Android 13 (Developer Preview 2) - android-13-samples/notification-runtime-permission at master ·…
Step by Step Explanation
Follow the steps provided below to make this application.
1. As of the writing of this article, Android 13 can only be used with the preview release of Android Studio. Therefore, you must go to this page, and download the Canary Build of Android Studio.
2. Once installed, you need to install the Android 13 SDK. You can do this by clicking Tools > SDK Manager. In the SDK Platforms tab, select Android 13. In the SDK Tools tab, select Android SDK Build-Tools 33. Click OK to install the SDK.
3. Once SDK is installed, open the Android Studio. Create new project with Empty Activity option.
4. First off, you need to change the target and compile SDK version of this app. Open
app/build.gradle and you would see something like this:
targetSdk to use the Android 13 SDK like shown in the code snippet below. Don’t forget to click Sync Now after.
5. Next, we need to declare the new notification runtime permission in our
6. Next, we need to update our layout file,
activity_main.xml. The image below shows how the layout will look like. It consists of a button that will request user for the notification permission to be granted. If user grants this permission, the app will show one notification. It also has a TextView that displays whether notification is currently enabled or not for your app.
Copy-paste the code snippet below to your
activity_main.xml file to create the above layout:
7. Finally, we need to update our
MainActivity.kt file. You can go ahead and copy-paste the code snippet below. But the most important thing to notice here is the usage of
POST_NOTIFICATIONS permission. It behaves exactly like any other runtime permission. But unless user grants it, your app will not be allowed to post any notification to user in Android 13.
8. That’s it! Now run your app and try it for yourself like this:
As always, thanks for reading!
Want to learn more about Android 13?
Check out all of our articles from “Exploring Android 13” series here: