ことで、この資料BLE(Bluetooth Low Energy)
のBluetoothチャット効果を達成するために、我々は通常BLEの一部に接続するために携帯電話を使用して携帯電話として機能することで、スマートまたはインテリジェントハードウェア・デバイス、次に通信する、ある客户端
、スマートデバイスが動作し服务端
、合格することは稀に有用BLEが通信するために2本の携帯電話をさせ、携帯電話は両方として動作することができます客户端
としても機能することができ服务端
まず、言葉は言っていない、レンダリングを見て
BLE最小サポートAndroid4.3(API = 18)だけでなく、サーバとして機能する場合はその最小サポートAndroid5.0(API = 21)
第二に、我々はAndroid6.0以上で動的なアプリケーションを実行するために必要なアクセス許可を追加する必要がありACCESS_FINE_LOCATION
、周囲のBluetoothデバイスを取得する権限を
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- android M 以上版本获取周边蓝牙设备必须定位权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
第三には、ブルートゥース、オープンブルートゥースを初期化します
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
- ブルートゥースをオンにします
/**
* 打开蓝牙
*/
public boolean enableBluetooth() {
if (bluetoothAdapter == null) return false;
if (!bluetoothAdapter.isEnabled()) {
return bluetoothAdapter.enable();
} else {
return true;
}
}
第四に、クライアント接続を待って、私たちのBLEサーバーを作成します。我々は、Bluetooth名を設定することができますBleChatServer
//开启BLE蓝牙服务
startAdvertising("BleChatServer");
- サービスコードは、オープンを呼び出します
/**
* 创建Ble服务端,接收连接
*/
public void startAdvertising(String name) {
//BLE广告设置
AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setConnectable(true)
.setTimeout(0)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.build();
AdvertiseData advertiseData = new AdvertiseData.Builder()
.setIncludeDeviceName(true)
.setIncludeTxPowerLevel(true)
.build();
bluetoothAdapter.setName(name);
//开启服务
BluetoothLeAdvertiser bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
bluetoothLeAdvertiser.startAdvertising(settings, advertiseData, advertiseCallback);
}
- BLEオープンコールバックサービスの成功、そして私たちは、同時に対話読み、サービスUUIDの書き込みが特性値を含めるために、当社のサービスのUUIDを公開する必要があります
/**
* Ble服务监听
*/
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Log.e(TAG, "服务开启成功 " + settingsInEffect.toString());
addService();
}
};
- サービスを追加UUID
//服务uuid
public static UUID UUID_SERVER = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
//读的特征值¸
public static UUID UUID_CHAR_READ = UUID.fromString("0000ffe3-0000-1000-8000-00805f9b34fb");
//写的特征值
public static UUID UUID_CHAR_WRITE = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");
/**
* 添加读写服务UUID,特征值等
*/
private void addService() {
BluetoothGattService gattService = new BluetoothGattService(UUID_SERVER, BluetoothGattService.SERVICE_TYPE_PRIMARY);
//只读的特征值
BluetoothGattCharacteristic characteristicRead = new BluetoothGattCharacteristic(UUID_CHAR_READ,
BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ);
//只写的特征值
BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(UUID_CHAR_WRITE,
BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ
| BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);
//将特征值添加至服务里
gattService.addCharacteristic(characteristicRead);
gattService.addCharacteristic(characteristicWrite);
//监听客户端的连接
BluetoothGattServer bluetoothGattServer = bluetoothManager.openGattServer(this, gattServerCallback);
//添加服务
bluetoothGattServer.addService(gattService);
}
gattServerCallback
コールバックアップクライアント接続
private BluetoothGattServerCallback gattServerCallback = new BluetoothGattServerCallback() {
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
ServerActivity.this.device = device;
String state = "";
if (newState == BluetoothProfile.STATE_CONNECTED) {
state = "连接成功";
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
state = "连接断开";
}
Log.e(TAG, "onConnectionStateChange device=" + device.toString() + " status=" + status + " newState=" + state);
}
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
String data = new String(value);
Log.e(TAG, "收到了客户端发过来的数据 " + data);
//告诉客户端发送成功
bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
}
};
第五に、UUIDおよびサービスここでは、この事の特性値を言及する必要があり
- BLEは新しい上にある複数のサービスサービスを、持っている
BluetoothGattService
、クライアントがUUIDで見つけることができます - AサービスはUUIDで機能を見つけるために最初のUUID値で見られる複数の特徴は、クライアントのサービスを持っています
第六は、BLEサービスが達成された、ここで終了するために、クライアントのスキャンは、このサービスを開くために見つけることができます
セブン、サーバーが終了した作成するために、次のステップでは、とのクライアントの接続をスキャンすることです
- 最初は、Bluetoothをオンにする必要があり、最初に参照する
二、三
ステップと、Android M
上記の、周囲のBluetoothデバイスに許可を得るために動的ポジショニングのために適用する必要があります
/**
* 扫描设备
*/
public void startScan() {
if (bluetoothAdapter == null) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
if (scanner != null) {
scanner.startScan(scanCallback);
}
} else {
bluetoothAdapter.startLeScan(leScanCallback);
}
}
//扫描的监听回调
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
//device就是周边的设备了
}
};
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
//device就是周边的设备了
}
};
八、接続、送信を確立し、サーバとのデータを受信します
//device就是我们扫描回调内拿到的设备(BleChatServer)
BluetoothGatt bluetoothGatt = device.getDevice().connectGatt(this, false, bluetoothGattCallback);
- コールバック接続ステータス
private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.e(TAG, "onConnectionStateChange 连接成功");
//查找服务
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_CONNECTING) {
Log.e(TAG, "onConnectionStateChange 连接中......");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e(TAG, "onConnectionStateChange 连接断开");
} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
Log.e(TAG, "onConnectionStateChange 连接断开中......");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
//设置读特征值的监听,接收服务端发送的数据
BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_CHAR_READ);
boolean b = bluetoothGatt.setCharacteristicNotification(characteristic, true);
Log.e(TAG, "onServicesDiscovered 设置通知 " + b);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
String data = new String(characteristic.getValue());
Log.e(TAG, "onCharacteristicChanged 接收到了数据 " + data);
}
};
- ここでは
UUID_SERVER
、UUID_CHAR_READ
私たちのサーバー設定で - 在发现服务回调这里,我们需要对我们在服务端设置的
读特征值
进行通知设置;这样当服务端写入了数据,就会回调我们的onCharacteristicChanged()
拿到数据
客户端发送数据给服务端,也就是往我们服务端定义的写特征值
写入数据
/**
* 发送数据
*
* @param msg
*/
public void sendData(String msg) {
//找到服务
BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
//拿到写的特征值
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_CHAR_WRITE);
bluetoothGatt.setCharacteristicNotification(characteristic, true);
characteristic.setValue(msg.getBytes());
bluetoothGatt.writeCharacteristic(characteristic);
Log.e(TAG, "sendData 发送数据成功");
}