实现效果
核心代码
添加权限
蓝牙通信,还是要在清单文件里注册蓝牙使用的权限。
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
布局文件
要添加1个Toolbar控件,和2个水平的TextView控件,具体布局可以见详细代码。但得注意,添加Toolbar前我们得添加依赖,即添加appcompat-v7相关版本。
蓝牙连接功能
要写蓝牙连接,需要通过3个线程来实现。分别为:1、 AcceptThread 收到连接,则保持此连接传给 ConnectedThread 。 2、ConnectThread 主动发起连接的线程 根据UUID 发起连接,连接成功则将连接传入ConnectedThread。3、ConnectedThread 管理连接的线程,管理连接好的双方,进行数据通信。输入输出流,接收数据,发送数据。
//以下为部分代码,完整代码见源码
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
//使用射频端口(RF comm)监听
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
蓝牙搜索设备功能
主要实现一个BroadcastReceiver 广播接收者。首先要注册广播,才能使用,添加蓝牙设备ACTION_FOUND等。其次就是这里广播接收,一旦开启广播搜索,并找到设备 接收到ACTION_FOUND的信息,则可以从BluetoothDevice.EXTRA_DEVICE中得到搜索到的设备信息,显示到屏幕上,如果是DISCOVERY_FINISHED,即结束搜索。
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
最后附上源码地址:https://gitee.com/ftlalala/BlueTooth