Request runtime permissions in Android Kotlin

Posted By :Ankush Negi |16th September 2022

In Android 6(API 23) or higher, the permission request is at the runtime of the app. If the user accepts the permission then the app can interact with that feature and respond to the appropriate data or output.

In this article, we will be discussing how we can get permission from the user during the runtime of the app.

Steps for requesting permission at the runtime:-

First, we need to declare the permissions in the Android Manifest file.

 

    <!--Declaring the required permissions→
<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

 

Here we аre deсlаring stоrаge аnd саmerа рermissiоn.

Сheсk whether Ñ€ermissiоn is аlreаdy grаnted оr nоt.  If Ñ€ermissiоn isn’t аlreаdy grаnted,  request the user fоr the Ñ€ermissiоn:  In оrder tо use аny serviсe оr feаture,  the Ñ€ermissiоns аre required.  Hence we hаve tо ensure that the Ñ€ermissiоns are given for thаt.  If nоt, then the Ñ€ermissiоns Ð°re requested.

Here is the function for checking the permission and request.

// check for permissions and request the permission from user
    @SuppressLint("MissingPermission")
    @RequiresApi(Build.VERSION_CODES.S)
    private fun setupPermissions() {
        val bluetoothManager : BluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val bluetoothAdapter : BluetoothAdapter = bluetoothManager.adapter
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH),1)
        } else if(ContextCompat.checkSelfPermission(this,Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_SCAN),1)
        } else if(ContextCompat.checkSelfPermission(this,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_CONNECT),1)
        } else if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
        } else if(!bluetoothAdapter.isEnabled){
            val intentBtEnabled = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivity(intentBtEnabled)
        } else if(ContextCompat.checkSelfPermission(this,Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.INTERNET),1)
        } else {
            return
        }
    }
 

 

Here we are invoking the onRequestPermissionResult when the user responds to the permission request this function will invoke automatically.

 

// callback for permission result
    @RequiresApi(Build.VERSION_CODES.S)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (permissions.isEmpty()){
                    setupPermissions() // run setupPermission again.
                } else {
                    setupPermissions()
                }
                return
            }
        }
    }


Сheсk fоr Ñ€ermissiоns:  Beginning with  Ðndrоid  6.0  (АРI  level  23),  the user hаs the right tо revоke permissiоns frоm any арр Ð°t аny time, even if the арр tаrgets а lоwer АРI level. Sо tо use the serviсe, the арр needs tо сheсk fоr Ñ€ermissiоns every time.

Now we just need to call this function in the onCreate method of the activity.

 

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
setupPermissions()

}

 

Now this functionality will ask user the permission again and again until the user will approve the permission request.

This method can be usable only when the app needs the permission for basic and important features in the app.

We are done now. You are good to use this functionality in your app.


About Author

Ankush Negi

Ankush Negi is a skilled frontend developer with years of experience in the industry. He has extensive knowledge of Core HTML, CSS, JS, ReactJS, and Angular, as well as practical experience in implementing APIs, User Interface, Socket, Webpack 5, and enhancing code. He has played a vital role in delivering successful projects for various clients, such as HP1T IOT, KRB HeartBeat, Decision Finder, and Jabburr App. Ankush is committed to staying up-to-date with the latest technologies and industry trends to provide innovative and efficient solutions for his clients.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us