LoginSignup
12
12

More than 5 years have passed since last update.

Android BLE メモ スキャンまで (API level 21対応版)

Last updated at Posted at 2016-10-31

AndroidでBLEを動作させるための備忘録として記載します。
自分で理解できることを優先していますので、不足分は補完してくださいませ。。。

マニュフェストへのパーミッション追加

AndroidManifestに”BLE使わせてくださいね”的なものを追加します。
位置に関する"ACCESS_COARSE_LOCATION"も必要となるので忘れずに。

AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth" />

インポート

BLEに必要なあれこれをimportします。

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;

変数宣言

BLE通信をするクラスのメンバとして追加。

private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private ScanCallback mScanCallback;

BluettoothAdapterの取得

final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

// Bluetoothサポートしているかのチェック
if (mBluetoothAdapter == null) {
    Toast.makeText(this, Bluetooth未サポート, Toast.LENGTH_SHORT).show();
    finish();
    return;
}

BluetoothLeScannerの取得

mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

コールバック

コールバック関数と動作を作成する。

private ScanCallback initCallbacks() {
    return new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            // デバイスが見つかった!
            if (result != null && result.getDevice() != null) {
                // リストに追加などなどの処理をおこなう
                //addDevice(result.getDevice(), result.getRssi());
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}

onCreateなどでコールバックをメンバに入れておく

mScanCallback = initCallbacks();

BLEスキャンの開始/停止

スキャンの開始

mBluetoothLeScanner.startScan(mScanCallback);

スキャンの停止

mBluetoothLeScanner.stopScan(mScanCallback);

以上。

12
12
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
12
12