Android Working With App Permission In Kotlin

The Word Permission means allowing sometime , to do a particular thing – it is consent or authorization given to perform any kind of action , Android apps are built to perform a set of actions, some of them requiring permissions from users .

With the introduction of Android 6.0 Marshmallow, Google has changed the way permissions are handled by the app , Before Marshmallow all permissions are granted by the system automatically .


From Marshmallow Android Permissions are divided into dangerous and normal Permission , The common thing in both the types is that they need to be defined in the Manifest file. 
  1. Normal Permission. 
  2. Runtime Permission ( Dangerous Permission ).

1. Normal Permission : 

  • These permissions allow access to data and actions that extend beyond your app's sandbox.
  • The system grants these permissions automatically
  • Poses Low or No Risk .
  • These include connecting to the internet, getting network, Bluetooth, wifi, and NFC information, setting alarms & wallpapers, and modifying audio settings on a device
  

2. Runtime Permission : 

  • Dangerous permissions are permissions which could potentially affect the user’s privacy or the device’s operation .
  • The user must explicitly agree to grant those permissions. 
  • Poses High Risk .
  • These include accessing the camera, contacts, location, microphone, sensors, SMS, and storage.


1. Declaring Permissions Needed by Your App In Apps Manifest


Add Permission to manifest . 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialsbuzz.permissionexample">

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

    <application
       ---------------------
	   ---------------->
 	    ----------------
       	 ---------------   
    </application>

</manifest>

2. Check is Permission Granted


Before Making Request check is Permission already granted .
private fun checkPermissionForReadExtertalStorage(): Boolean {
	return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
		(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
				|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
	} else false
}

3. Requesting Permissions for Your App


Making Request by passing request code .

private fun requestPermission() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
		requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
				REQUEST_WRITE_PERMISSION)
	} 
}

4. Handling Permissions Granted to Your App


Override the onRequestPermissionsResult callback of AppCompatActivity Inside this we will get to know the status of requested permission .
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
	super.onRequestPermissionsResult(requestCode, permissions, grantResults)
	if (grantResults.size > 0) {
		if (requestCode == REQUEST_WRITE_PERMISSION)
			if (grantResults[0]
					== PackageManager.PERMISSION_GRANTED) {
				// permission granted
				label?.setText(R.string.permission_granted)
			} else {
				// permission denied
				label?.setText(R.string.permission_denied)
			}
	}
}

MainActivity


Complete MainActivity Code .
package com.tutorialsbuzz.permissionexample

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat


class MainActivity : AppCompatActivity() {

    private var label: TextView? = null

    companion object {
        const val REQUEST_WRITE_PERMISSION = 100
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        label = findViewById(R.id.label)
        val requestBtn = findViewById<Button>(R.id.requestBtn)
        requestBtn.setOnClickListener { v: View? ->
            if (checkPermissionForReadExtertalStorage()) {
                // Permission Already Granted
                label?.setText(R.string.permission_granted)
            } else {
                // Make Permission Request
                requestPermission()
            }
        }
    }

    fun checkPermissionForReadExtertalStorage(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        } else false
    }

    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_WRITE_PERMISSION)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.size > 0) {
            if (requestCode == REQUEST_WRITE_PERMISSION)
                if (grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    // permission granted
                    label?.setText(R.string.permission_granted)
                } else {
                    // permission denied
                    label?.setText(R.string.permission_denied)
                }
        }
    }
}



No comments:

Post a Comment