通信是建立在两个设备上的,其中一个为服务端,一个为客户端。
服务端主要的任务是等待连接,客户端主动发起连接的操作
接下来先说服务端的过程
蓝牙通信的uuid是固定的
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
register();//注册一系列的广播
//得到蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {//为空表示设备不支持蓝牙功能
if (!mBluetoothAdapter.enable()) {
mBluetoothAdapter.enable();//打开蓝牙
} else {
mBluetoothAdapter.startDiscovery();//开始扫描
}
}
private void register() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态的广播
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//设备蓝牙状态的广播
filter.addAction(BluetoothDevice.ACTION_FOUND);//发送设备的广播
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//查找附近设备结束的广播
filter.addAction("android.bluetooth.device.action.PAIRING_REQUEST");//配对请求的广播
registerReceiver(mBroadcastReceiver, filter);
}
接下来看广播接收类的操作
protected BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 获取蓝牙设备
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
int state = bluetoothDevice.getBondState();
switch (state) {
case BluetoothDevice.BOND_BONDED:
Log.e("ida", "绑定成功");
connect();//进行通信的代码
break;
case BluetoothDevice.BOND_BONDING:
Log.e("ida", "BOND_BONDING正在绑定");
break;
case BluetoothDevice.BOND_NONE:
break;
}
}
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
LogUtils.d(bluetoothDevice.getName() + "---" + bluetoothDevice.getAddress());
if (bluetoothDevice.getName() != null) {
if (bluetoothDevice.getName().equals("我的")) {
bluetoothDevice.createBond();
}
}
}
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
switch (blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
break;
case BluetoothAdapter.STATE_ON:
mBluetoothAdapter.startDiscovery();
Log.e("dalai", "打开了蓝牙设备");
//startScanning();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
break;
case BluetoothAdapter.STATE_OFF:
break;
}
}
if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
LogUtils.d(action);
mBluetoothAdapter.cancelDiscovery();
}
if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {//本来想写自动配对的,但pin值始终不正确,只能弹出配对框手动配对
LogUtils.d("配对请求的广播");
// bluetoothDevice.setPairingConfirmation(true);//确认配对
// bluetoothDevice.setPin("0000".getBytes());
}
}
};
private void connect() {
try {
btServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BluetoothChat", MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
try {
bluetoothSocket = btServerSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
if (bluetoothSocket != null) {
try {
InputStream inputStream = bluetoothSocket.getInputStream();
OutputStream outputStream = bluetoothSocket.getOutputStream();
byte[] bytes = new byte[4];
inputStream.read(bytes);
String str = new String(bytes, "utf-8");
inputStream.close();
btServerSocket.close();
Log.e("ida", "this is read---" + str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
接下来看客户端的代码
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
if (device.getName().equals("BleServer")) {
address = device.getAddress();
}
}
if (address != null) {
device = mBluetoothAdapter.getRemoteDevice(address);
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
if (socket != null) {
socket.connect();
if (socket.isConnected()) {
Log.e("ida", "连接成功");
OutputStream osm = socket.getOutputStream();
osm.write("1234".getBytes());
osm.close();//及时关闭
socket.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
这样就可以通信了,在实际应用中要服务端一般要在service中完成,还要及时关闭输入输出流以及socket连接
良好的代码规范也很重要