需要bluecove.jar
下载地址:
bluecove-2.1.0.jar
bluecove-2.1.1-SNAPSHOT(x64).jar
作为服务端:
public class BluetoothJavaServer {
private StreamConnectionNotifier mStreamConnectionNotifier = null;
private StreamConnection mStreamConnection = null;
public static void main(String[] args) {
new BluetoothJavaServer();
}
public BluetoothJavaServer() {
try {
// 服务器端的UUID必须和手机端的UUID相一致。手机端的UUID需要去掉中间的-分割符。
mStreamConnectionNotifier = (StreamConnectionNotifier) Connector
.open("btspp://localhost:0000110100001000800000805F9B34FB");
} catch (Exception e) {
e.printStackTrace();
}
// 开启线程读写蓝牙上接收和发送的数据。
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("服务器端开始监听...");
while (true) {
mStreamConnection = mStreamConnectionNotifier.acceptAndOpen();
System.out.println("接受连接");
InputStream is = mStreamConnection.openInputStream();
byte[] buffer = new byte[1024];
System.out.println("开始读数据...");
// 读数据。
int len=0;
while ((len=is.read(buffer)) != -1) {
String s = new String(buffer,0,len);
System.out.println(s);
}
is.close();
mStreamConnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
作为客户端:
分为3步:
1.扫描蓝牙设备代码:
扫描的设备存放在devicesDiscovered中
public class RemoteDeviceDiscovery {
public static final Vector/*<RemoteDevice>*/ devicesDiscovered = new Vector();
public static void main(String[] args) throws IOException, InterruptedException {
final Object inquiryCompletedEvent = new Object();
devicesDiscovered.clear();
DiscoveryListener listener = new DiscoveryListener() {
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}
public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized(inquiryCompletedEvent){
inquiryCompletedEvent.notifyAll();
}
}
public void serviceSearchCompleted(int transID, int respCode) {
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};
synchronized(inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}
}
获取已配对设备
//获取已配对设备 DiscoveryAgent.PREKNOWN表示已配对的所有设备;
//DiscoveryAgent.CACHED表示配对已连接设备
RemoteDevice[] remoteDevices = LocalDevice.getLocalDevice().getDiscoveryAgent()
.retrieveDevices(DiscoveryAgent.CACHED);
2.查询符合条件的设备:通过uuid在设备列表中查询目标设备,查询到的设备放在serviceFound中
public class ServicesSearch {
private static final UUID OBEX_OBJECT_PUSH = new UUID("0000110100001000800000805F9B34FB",false);
public static final Vector<String> serviceFound = new Vector();
public static void main(String[] args) throws IOException, InterruptedException {
// First run RemoteDeviceDiscovery and use discoved device
// RemoteDeviceDiscovery.main(null);
serviceFound.clear();
UUID serviceUUID = OBEX_OBJECT_PUSH;
if ((args != null) && (args.length > 0)) {
serviceUUID = new UUID(args[0], false);
}
final Object serviceSearchCompletedEvent = new Object();
DiscoveryListener listener = new DiscoveryListener() {
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
}
public void inquiryCompleted(int discType) {
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
serviceFound.add(url);
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
} else {
System.out.println("service found " + url);
}
}
}
public void serviceSearchCompleted(int transID, int respCode) {
System.out.println("service search completed!");
synchronized(serviceSearchCompletedEvent){
serviceSearchCompletedEvent.notifyAll();
}
}
};
UUID[] searchUuidSet = new UUID[] { serviceUUID };
int[] attrIDs = new int[] {
0x0100 // Service name
};
for(Enumeration en = RemoteDeviceDiscovery.devicesDiscovered.elements(); en.hasMoreElements(); ) {
RemoteDevice btDevice = (RemoteDevice)en.nextElement();
synchronized(serviceSearchCompletedEvent) {
System.out.println("search services on " + btDevice.getBluetoothAddress() + " " + btDevice.getFriendlyName(false));
LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
serviceSearchCompletedEvent.wait();
}
}
}
}
3.传输数据,通过输出流传输数据
public class BluetoothClient {
private static String serverUUID = "0000110100001000800000805F9B34FB";
private static String serverURL = null;
public static void main(String[] args) throws Exception {
SystemTray systemTray = SystemTray.getSystemTray();
ImageIcon imageIcon = new ImageIcon(BluetoothClient.class.getResource("/icon/1.png"));
TrayIcon trayIcon = new TrayIcon(imageIcon.getImage(),"");
systemTray.add(trayIcon);
}
public static Vector<String> getServerURL(String serverUUID) throws Exception {
ServicesSearch.main(new String[] { serverUUID });
if (ServicesSearch.serviceFound.size() == 0) {return new Vector<String>();}
return ServicesSearch.serviceFound;
}
public static OutputStream getOutputstream(String serverURL) throws Exception {
StreamConnection connection = (StreamConnection) Connector.open(serverURL);
return connection.openOutputStream();
}
}