开发一个蓝牙扫描的demo,需要依赖 bluecove-2.1.1.jar
window能正常执行,linux报错
代码
import javax.bluetooth.*;
public class TestBlueTooth {
public static void main(String[] args) throws Exception {
//初始化本地设备
//获取本地蓝牙适配器
LocalDevice localDevice = LocalDevice.getLocalDevice();
//设置设备可见性
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
//获取本地设备地址
String bluetoothAddress = localDevice.getBluetoothAddress();
System.out.println("本地蓝牙地址:"+bluetoothAddress);
System.out.println("开启蓝牙扫描");
//启动设备发现
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
TestDeviceListener testDeviceListener = new TestDeviceListener();
agent.startInquiry(DiscoveryAgent.GIAC,testDeviceListener);
//等待蓝牙扫描
System.out.println("等待蓝牙扫描30s......");
Thread.sleep(30000);
agent.cancelInquiry(testDeviceListener);
}
}
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import java.io.IOException;
public class TestDeviceListener implements DiscoveryListener {
//发现设备
@Override
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
String name = null;
try {
name = btDevice.getFriendlyName(false);
} catch (IOException e) {
e.printStackTrace();
}
String address = btDevice.getBluetoothAddress();
System.out.println("发现设备: "+name+" ("+address+")");
}
//服务搜索完成
@Override
public void servicesDiscovered(int i, ServiceRecord[] serviceRecords) {
}
//服务搜索完成
@Override
public void serviceSearchCompleted(int i, int i1) {
}
//设备发现完成
@Override
public void inquiryCompleted(int i) {
System.out.println("设备发现完成");
}
}
报错
检查BlueZ 是已经有的
查找系统上是否存在 libbluetooth.so 这个库文件
find / -name libbluetooth.so* 2>/dev/null
是有这个文件的
将这个库链接到 /usr/lib/ 目录下 再运行就可以了
sudo ln -s /usr/lib/x86_64-linux-gnu/libbluetooth.so.3 /usr/lib/libbluetooth.so
总结:库文件没有被正确引用导致的报错