user1977132
user1977132

Reputation: 497

Could not find class 'android.bluetooth.BluetoothManager'

When the activity is opened on a phone with API < 18 it gives the exception

Could not find class 'android.bluetooth.BluetoothManager'

Despite the following check:

private void activateBluetoothSmart() {

    if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) && (Build.VERSION.SDK_INT >= 18)) {
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        myBluetoothAdapter = bluetoothManager.getAdapter();

        if (myBluetoothAdapter == null || myBluetoothAdapter.isEnabled() == false) {
            Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT);
        } else {
            scanForHrm();
        }
    }
}

Apart from why the version check is being ignored I don't understand why the code is being called when the activity is opened, it should only be called when the user presses a button.

Are all classes 'preloaded' when an activity is opened? I've looked at this question: NoClassDefFoundError during class load for BLE scanning callback which suggests the version code check as well as the feature check but haven't found anything else.

Upvotes: 2

Views: 851

Answers (1)

user1977132
user1977132

Reputation: 497

So the problem is that all referenced classes are imported when the activity is opened. The solution was to create a new class and to place all the Bluetooth LE related code within that new class and then call methods of that new class with the correct condition checks.

I think this works because of "lazy class loading", the referenced classes are now within a new class and they only get imported when that class is called.

Upvotes: 1

Related Questions