蓝牙那些事之通讯篇

    讲到通讯,主要也就是BluetoothServerSocket和BluetoothSocket这两个类,其实和serversocket和socket用法都一样,在建立通讯时,需要建立两个socket,一个在客户端,一个在服务端。

服务端代码:

 1 //开启服务器端线程
 2         private class serverThread extends Thread{
 3             private BluetoothAdapter btadapter;
 4             public serverThread(BluetoothAdapter btadapter) {
 5                 super();
 6                 this.btadapter = btadapter;
 7             }
 8             @Override
 9             public void run() {
10                     try {
11                         System.out.println("===btadapter==="+btadapter);
12                         mServerSocket=btadapter.listenUsingRfcommWithServiceRecord("myblue", UUID.fromString(FLAG_BY_UUID));
13                         socket = mServerSocket.accept();
14                         System.out.println("服务器已开启了...");
15                     } catch (Exception e) {
16                         System.out.println("服务器连接失败...");
17                         e.printStackTrace();
18                 }   
19             }
20         }    

和google api有点不同,也许他那个写的更严谨一些,可以及时释放资源

客户端:

 1 //开启客户端线程
 2     private class clientThread extends Thread{
 3         private BluetoothDevice de;
 4         public clientThread(BluetoothDevice de) {
 5             super();
 6             this.de = de;
 7         }
 8 
 9         @Override
10         public void run() {
11             bluetoothadapter.cancelDiscovery();
12             try {
13                 socket=de.createRfcommSocketToServiceRecord(UUID.fromString("FLAG_BY_UUID"));
14                 System.out.println("============socket==="+socket+"====device======="+de);
15                 //连接设备
16                 System.out.println("======连接前======");
17                 socket.connect();
18                 System.out.println("======连接后======");
19                 handler.sendEmptyMessage(3);
20             } catch (Exception e) {
21                 e.printStackTrace();
22             }
23         }
24     }

UUID:00001101-0000-1000-8000-00805F9B34FB 这个uuid很关键,看到有些朋友写的uuid不同,导致出现不同的结果,但是关键在哪我也不是很清楚

当客户端与服务器端建立连接后,需要发送数据和接收数据,这里是通过流的实现数据的接收与发送

接收数据的线程:

 1  //读取数据  
 2    private class readThread extends Thread {   
 3     private Context con;
 4     
 5     public readThread(Context con) {
 6         super();
 7         this.con = con;
 8     }
 9 
10     public void run() {  
11            byte[] buffer = new byte[124];  
12            int bytes;  
13            InputStream mmInStream = null;  
14            try {  
15                 mmInStream = socket.getInputStream();  
16            } catch (IOException e1) {  
17                 e1.printStackTrace();  
18            }     
19            while (true) {  
20                try {  
21                        if((bytes = mmInStream.read(buffer))>0){   
22                         byte[] buf_data = new byte[bytes];  
23                         for(int i=0; i<bytes; i++){  
24                             buf_data[i] = buffer[i];  
25                         }  
26                         dd(con,buf_data);
27                       }  
28                    } catch (IOException e) {  
29                     try {  
30                         mmInStream.close();  
31                     } catch (IOException e1) {  
32                         e1.printStackTrace();}  
33                        break;  
34                    }  
35                }  
36           }  
37      }  
View Code

接收到的数据是byte,需要自己转换成相应的进制....

发送数据:

 1 //发送数据  
 2    private void sendTextToOther(String msg){     
 3        if (socket == null){  
 4            Utils.getinstance().getStr(SearchBlueToothActivity.this, "请先连接设备"); 
 5            return;  
 6        }  
 7        try {                 
 8            OutputStream os = socket.getOutputStream();   
 9            System.out.println("========发送的数据是============="+msg.getBytes());
10            os.write(msg.getBytes());  
11        } catch (IOException e) {  
12            e.printStackTrace();  
13        }             
14    }

ok,到这里已经可以实现两部设备的通讯了....

原文地址:https://www.cnblogs.com/yrhua/p/3792296.html