やりたいこと
- 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つ目のやり方でやりましょうということでした。