1 year ago

#384746

test-img

Dylon Jaynes

How do I get reference to an application in a bluetooth service?

I am trying to use requestPermissions() in my bluetooth service but I can't seem to get an activity reference in my service and I've heard that is bad practice to do so anyways, so how can I use requestPermissions within my bluetooth service?

Here is my bluetooth service connection code:

@RequiresApi(Build.VERSION_CODES.S)
    fun connect(device: BluetoothDevice): Boolean {
        broadcastUpdate(ACTION_CHECK_BT_PERMISSION)
        bluetoothAdapter?.let {
            return try {
                // Connect to devices gatt server.
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.BLUETOOTH_CONNECT
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(--ACTIVITY_NEEDED_HERE--, arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 1)
                    // 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 true
                }
                bluetoothGatt = device.connectGatt(applicationContext, false, gattCallback)
                true
            } catch (exception: IllegalArgumentException) {
                Log.d(TAG, "Device not found with provided address.")
                false
            }
            // connect to the GATT server on the device
        } ?: run {
            Log.d(TAG, "BluetoothAdapter not initialized")
            return false
        }
    }

android

kotlin

bluetooth-lowenergy

0 Answers

Your Answer

Accepted video resources