1

I am making Bluetooth Low Energy Android app and I do not want to see SecurityException like this: Security Exception shows

Looks like that the easist way to handle the problem(warning?) is adding

@SuppressLint("MissingPermission")

and second choice is adding check permission EACH statement(method) which may occur SecurityException with help context action(a.k.a quick fix) from Android Studio

like:

FROM

bluetoothGatt?.discoverServices()

TO

    if (ActivityCompat.checkSelfPermission(
         this,
         Manifest.permission.BLUETOOTH_CONNECT
      ) != PackageManager.PERMISSION_GRANTED
   ) {
      // TODO: Consider calling
      //    ActivityCompat#requestPermissions
      // here to request the missing permissions, and then overriding
      //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
      //                                          int[] grantResults)
      // to handle the case where the user grants the permission. See the documentation
      // for ActivityCompat#requestPermissions for more details.
      return
   }
   Log.i(TAG, "Attempting to start service discovery:"+
         bluetoothGatt?.discoverServices() )
}

but it doens't look right way, I think...

So I want to make general try-catch function for handling same SecurityException along those different methods :

bluetoothGatt?.discoverServices()
bluetoothGatt?.disconnect()
bluetoothAdapter?.disable()
ScanResult.device.name
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)

These methods are come from different classes and produce different return value but have same SecurityException.

I think if there is proper function which handles SecurityException, then code duplication goes minimum and code will be reproductive.

How can I make function that handles along different methods causing SAME EXCEPTION? like :

fun foo(m : differentMethods) : differentReturnValue{
    try{
        return m(bar)
    } catch(e: SecurityException){
        e.printStackTrace()
    }
}

I tried to make function experimentally that gets parameter for function with handling exception and returns value but I don't know how to make it.

kat opp
  • 11
  • 2
  • You can mark the whole class as requiring that permission with `@RequiresPermission`. Encapsulate all your functions that require this permission into this one class, and only instantiate the class after you have confirmed the permission is granted. Then you can freely use these functions without worrying about SecurityExceptions. – Tenfour04 Dec 15 '22 at 04:10

1 Answers1

0

You could use Thread.setDefaultUncaughtExceptionHandler

Visit here for more details: Using Global Exception Handling on android

Alan Lu
  • 81
  • 1
  • 5