Android server端代码:
public class BluetoothServerThread extends Thread{
private BluetoothAdapter adapter = null;
private UUID uuid = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
private BluetoothServerSocket serverSocket;
@Override
public void run() {
try{
adapter = BluetoothAdapter.getDefaultAdapter();
//没有蓝牙设备
if(adapter == null){
throw new RuntimeException("Bluetooth not support!");
}
//打开蓝牙
if(!adapter.isEnabled()){
adapter.enable();
}
serverSocket = adapter.listenUsingRfcommWithServiceRecord("Name", uuid);
while(true){
BluetoothSocket socket = serverSocket.accept();
executorService.execute(new SocketThread(socket));
}
}catch(Exception ex){
logger.error("Run BluetoothServerThread Error", ex);
stopServer();
}
}
public void stopServer(){
if(serverSocket != null){
try {
serverSocket.close();
serverSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
SocketThread代码:
class SocketThread implements Runnable{
private BluetoothSocket socket;
public SocketThread(BluetoothSocket socket){
this.socket = socket;
}
@Override
public void run() {
BufferedReader reader = null;
PrintWriter writer = null;
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true){
String msg = reader.readLine();
logger.info(msg);
writer.write("This message from server\r\n");
writer.flush();
}
}catch(Exception ex){
logger.error("SocketThread Error", ex);
if(socket != null){
try {
socket.close();
socket = null;
} catch (IOException ex2) {
logger.error("Close Socket Error", ex2);
}
}
}
}
}
PC 客户端代码:
UUID uuid = new UUID("04c6093b00001000800000805f9b34fb", false);
DiscoveryAgent agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
String connectionURL = agent.selectService(uuid, ServiceRecord.AUTHENTICATE_ENCRYPT, false);
StreamConnection connection = null;
PrintWriter writer = null;
BufferedReader reader = null;
try{
connection = (StreamConnection)Connector.open(connectionURL);
reader = new BufferedReader(new InputStreamReader(connection.openInputStream()));
writer = new PrintWriter(new OutputStreamWriter(connection.openOutputStream()));
writer.write("This message from client\r\n");
writer.flush();
String data = reader.readLine();
System.out.println(data);
}catch(Exception ex){
ex.printStackTrace();
}