How do I create a single permission check in my android app?

I am programming an app that connects to a device via Bluetooth, but every time I want to do something with the BluetoothDevice I have to insert a permission check like this (Kotlin):

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(
        this,
        arrayOf(Manifest.permission.BLUETOOTH_CONNECT),
        42
    )
}

Is there a workaround with one single permission check in the beginning of the app?

Thank you!

>Solution :

We have to check permission granted, otherwise it may crash your app.
but we can do in very handy way in Kotlin.
Follow below steps…

In your MainActivity or Very first activity, ask Bluetooth permission like below.

  1. Create Permission Callback in Activity.

       private val requestPermissionsLauncher =  registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
         if (permissions.all { it.value }) Toast.makeText(
             this,
             "Permission Granted",
             Toast.LENGTH_SHORT
         ).show()
         else Toast.makeText(this, "not accepted all the permissions", Toast.LENGTH_LONG).show()
     }
    
  2. Request a permission in onCreate method of Activity.

     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
    //your code
    
       requestPermissionsLauncher.launch(
          arrayOf(android.Manifest.permission.BLUETOOTH_CONNECT)
    ) //asking permission whatever we need to run app.
    }
    
  3. Create a kotlin Extension function to make sure to run only on Bluetooth permission is Granted.

     fun <T> Context.runOnBluetoothPermission(block: () -> T) {
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
         block()
     } else {
         Toast.makeText(
             this,
             "Bluetooth permission need to work this.",
             Toast.LENGTH_SHORT
         ).show()
     }
     }
    
  4. Use it extension function wherever you need.

example :

In SecondActivity.kt

  class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //ui functions
        //apicalls if any

        //functions that only run on Bluetooth permission
        runOnBluetoothPermission{
            getAllBluetoothDevices()
        }
    }
    
    private fun getAllBluetoothDevices(){
        //your code to get all bluetooth devices.
    }
}

Leave a Reply