LoginSignup
6
3

More than 5 years have passed since last update.

【Android】BluetoothAdapterを取得する2つの方法

Posted at

やりたいこと

  • Bluetoothでいろいろやるために、BluetoothAdapterを取得したい

1つ目のやりかた

  • BluetoothManagerを利用する
// API Level 23以上
BluetoothManager bluetoothManager = Context.getSystemService(BluetoothManager.class)
// API Level 1以上
BluetoothManager bluetoothManager = (BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);

BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

2つ目のやりかた

  • BluetoothAdapterのstaticメソッドを利用する
// null が返ってくる可能性有り
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

どっちがいいの?

公式リファレンスを見ると、

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.

基本的には1つ目のやり方で、
JELLY_BEAN_MR1以下 つまりAndroid4.2.2以下は2つ目のやり方でやりましょうということでした。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3