Open In App

Android Run Time Permissions using Jetpack Compose

Improve
Improve
Like Article
Like
Save
Share
Report

There are many features within android applications that require permissions to be granted by the user. For granting these permissions during runtime, runtime permissions are used within android applications. These permissions are called when the user wants to use any specific feature. Before using that feature permission is requested from the user. This type of permission requested during runtime is called runtime permission. In this article, we will take a look at How to use runtime permissions in android applications using Jetpack Compose

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to app>java>your app’s package name>ui.theme>Color.kt file and add below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Adding permission in AndroidManifest.xml file

Navigate to app>manifest>AndroidManifest.xml and add the below permissions in the manifest tag. 

XML




<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.newcanaryproject
 
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.Manifest
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Password
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.newcanaryproject.ui.theme.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background
                // color for our application
                Surface(
                    // on below line we are specifying
                    // modifier and color for our app
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
 
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying top bar.
                        topBar = {
 
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying
                                // title for our top bar.
                                title = {
 
                                    // in the top bar we are specifying tile as a text
                                    Text(
 
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "Runtime permissions",
 
                                        // on below line we are specifying modifier
                                        // to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
                        // on below line we are calling session
                        // management method and passing
                        // shared preferences to it.
                        runtimePermissions()
                    }
                }
            }
        }
    }
 
    // on below line we are calling on
    // request permission result method.
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
 
        // in this method we are checking if the request code
        // which we have passed 101 is same.
        if (requestCode == 101) {
            // if request code is 101 and permissions are granted.
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 
                // on below line we are displaying a toast message.
                Toast.makeText(this, "Storage permission granted", Toast.LENGTH_SHORT).show()
            } else {
                // on below line we are displaying a toast message.
                Toast.makeText(this, "Storage permission denied", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
 
// on below line we are creating a
// method as run time permission.
@Composable
fun runtimePermissions() {
     
    // on below line we are creating a variable
    // for activity and initializing it.
    val activity = (LocalContext.current as? Activity)
 
    // on below line we are creating a column.
    Column(
 
        // on below line we are adding modifier to
        // add max width, max size and max height
        // for our column.
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .fillMaxSize(),
 
        // on below line we are adding horizontal alignment.
        horizontalAlignment = Alignment.CenterHorizontally,
 
        // on below line we are adding
        // vertical arrangement to center.
        verticalArrangement = Arrangement.Center
    ) {
        // on below line we are adding a text
        Text(
            // in this we are specifying text as
            // Runtime permissions in android
            // on below line.
            text = "Runtime permissions in Android",
 
            // on below line we are adding font style.
            fontStyle = FontStyle.Normal,
 
            // on below line we are adding
            // font weight on below line as bold.
            fontWeight = FontWeight.Bold,
 
            // on below line we are adding
            // green color to our text
            color = greenColor,
 
            // on below line we are adding
            // font size to our text.
            fontSize = 20.sp
        )
 
        // on below line we are adding spacer between text and button.
        Spacer(modifier = Modifier.height(50.dp))
 
        // on below line we are creating a button
        Button(
            // on below line we are adding a modifier for our
            // button and adding a max width and padding to it.
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
 
            // on below line we are adding on click for our button.
            onClick = {
                // in the on click method we are calling check permission
                // method to check the permission
                checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 101, activity!!)
            }) {
            // on below line we are creating a text for our button on below line and adding a padding to it.
            Text(modifier = Modifier.padding(6.dp), text = "Request Storage permission")
        }
    }
}
 
// on below line we are creating a check permission method to check the permissions.
fun checkPermission(permission: String, requestCode: Int, activity: Activity) {
    // on below line we are checking if the permission is denied.
    if (ContextCompat.checkSelfPermission(
            activity,
            permission
        ) == PackageManager.PERMISSION_DENIED
    ) {
        // if the permission is denied we are calling
        // request permission method to request permissions.
        ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode)
    } else {
        // this method will be called if the permissions are already granted.
        // On below line we are displaying a toast message if permissions are granted.
        Toast.makeText(activity, "Permission already granted..", Toast.LENGTH_SHORT).show()
    }
}


Now run your application to see the output of it. 

Output: 



Last Updated : 28 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads