In this quick article, I’ll try to show you an easy way of how you can ask Android runtime permissions using Kotlin extension functions. Almost in every android app, we need to ask some permission from the user. Asking runtime permissions is a common task in android and different developers use different approaches.
The traditional way of asking android runtime permission
There are developers who still use uses the old-traditional way of asking android runtime permissions. Now let’s say I’m asking storage for read and write permission.
The above example asks successfully storage permission to the user but can we improve it? Because there is always a better way to solve the problem.
Creating activity class extension function for asking runtime Permission
In this method, we’ll try to write an extension function for an Activity class. I can show you how to ask for runtime permission with this approach.
After adding the extension functions, we can directly use the isHasPermission and askPermission into an Activity class and use it like this:
Nailed it 🔨 right! We have a solution from which we can easily ask runtime permission. Wait! this solution only works for kotlin developers. Let us take this example a little further and try to write these utility methods for Java developers.
Write a Java base activity class for asking the runtime permission
Let us start this method by creating a new Java BaseActivity class. All of our activities which needs to ask permission must extend with this BaseActivity class.
Next, we want the MainActivity to extend with BaseActivity class. After extending with BaseActivity the MainActivity able to use all the protected methods inside the class.
So, what do you think about asking runtime permissions with this approach? I excited to get your feedback or tips to improve those methods even further. Please let me know via the comments section.
Thank you for being here and keep reading…