[JAVA] [Android] Two ways to get a Bluetooth Adapter

Thing you want to do

――I want to get a Bluetooth Adapter to do various things with Bluetooth

The first way

--Use Bluetooth Manager

//API Level 23 or higher
BluetoothManager bluetoothManager = Context.getSystemService(BluetoothManager.class)
//API Level 1 or higher
BluetoothManager bluetoothManager = (BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);

BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

The second way

--Use the static method of BluetoothAdapter

//Null may be returned
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

Which one is better?

If you look at the Official Reference,

To get a BluetoothAdapter representing the local Bluetooth adapter, call the getAdapter() function on BluetoothManager. On JELLY_BEAN_MR1 and below you will need to use the static getDefaultAdapter() method instead.

Basically the first way, JELLY_BEAN_MR1 or less, that is, Android 4.2.2 or less, let's do it in the second way.

Recommended Posts

[Android] Two ways to get a Bluetooth Adapter
Two ways to start a thread in Java + @
Sample to get WiFi, Bluetooth beacon, sensor information on Android
[Rails] Two ways to write form_with
[Kotlin] 3 ways to get Class from KClass
Android Easily give a "press" to a button
A note about adding Junit 4 to Android Studio
[Android] Inherit ImageView to create a new class
[Android] How to convert a character string to resourceId
How to get a heapdump from a Docker container
3 ways to import the library in Android Studio
[Android] Implement a function to display passwords quickly
[Android / Java] Set up a button to return to Fragment
How to delete custom Adapter elements using a custom model
[Java] How to get a request by HTTP communication
[Android] How to get the setting language of the terminal
Fargate to get a rough idea in relation to EC2
How to get started with creating a Rails app
[Introduction to Android application development] Let's make a counter