BluetoothAdapter.getDefaultAdapter() has been deprecated - Flutter

2.8k Views Asked by At

I'm having tough time understanding a small thing.

Upon running my code, I'm getting following error

C:\Users\faiza\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\permission_handler-6.1.3\android\src\main\java\com\baseflow\permissionhandler\ServiceManager.java:152:
warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();                                                                  ^

It is obvious, I'm getting this error because BluetoothAdapter method use in ServiceManager.java got deprecated as mentioned in docs (https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#getDefaultAdapter()). My compileSdkVersion is 31.

Here is how isBluetoothServiceEnabled function looks like in ServiceManager.java

 private boolean isBluetoothServiceEnabled() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.isEnabled();

        // --- Solution #1 (Didn't work)
        // val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE);
        // bluetoothManager.getAdapter().isEnabled();
        
        // --- Solution #1 (Didn't work)
        // if (Build.VERSION.SDK_INT >= 31) {
        // bluetoothManager = BluetoothManager.getAdapter();
        // return bluetoothManager;
        // } else {
        // bluetoothManager = BluetoothAdapter.getDefaultAdapter();
        // return bluetoothManager;
        // }
    }

Now upon searching on google I found following solutions. Everyone of them is giving error. https://stackoverflow.com/a/69894425/7290043 https://stackoverflow.com/a/52231933/7290043

1

There are 1 best solutions below

1
On

I added @SuppressWarnings("deprecation") right above the function and that worked for me.