'How to check the permission for Bluetooth outside a activity in Android

Im currently developing an Android app, which transmits data via Bluetooth. I followed the Android documentation on Bluetooth, which seems to be created before the release of Android 12. Therefore there is no permission Check included. The problem is that createRfcommSocketToServiceRecord(), connect() and close() need several permissions.

    public ClientThread(BluetoothDevice host) throws IOException {
        BluetoothSocket socketKandidat = null;
        this.host = host;
        try {
            socketKandidat = host.createRfcommSocketToServiceRecord(uuid); //requires BLUETOOTH_Connect
        } catch (IOException e) {
            Log.e(TAG, "Fehler beim erstellen des btSockets", e);
            throw e;
        }
        hostSocket = socketKandidat;
    }

    @Override
    public void run() {
        btAdapter.cancelDiscovery(); //requires BLUETOOTH_SCAN
        try {
            hostSocket.connect(); //requires BLUETOOTH_CONNECT
        } catch (IOException verbindungsFehler) {
            Log.e(TAG, "Verbindungsaufbau mit Host fehlgeschlagen", verbindungsFehler);
            try {
                hostSocket.close();
            } catch (IOException abbruchFehler) {
                Log.e(TAG, "Fehler beim schließen der Verbindung zum Host", abbruchFehler);
            }
            return;
        }

        beobachter.erhalteHostSocket(hostSocket);
    }

My approach to this would be to pass the application context, since the class is several layers appart from any Object which is part of the lifecycle. I allready do a permission check for all the required permissions at the start, therefore these checks should be obsolete, if the user is not vicious. Is there a better approach to this problem without creating a whole new service class?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source