A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 佩恩六道 中级黑马   /  2017-9-9 16:14  /  1887 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

        随着物联网的发展,智能家居、智能穿戴、智能车载等应用也越来越广泛,作为开发人员,蓝牙这一块的需求也越来越多,现在就简单介绍一下蓝牙开发的过程

          首先,要使用蓝牙开发,必须在清单文件加入蓝牙的响应权限,并且在系统6.0之后,还必须加上地图的权限

       1、使用蓝牙的响应权限

XML/HTML代码
  • <uses-permission android:name="android.permission.BLUETOOTH"/>      
  • <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>   

       2、配置本机蓝牙模块

Java代码
  • BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();   
  • //直接打开系统的蓝牙设置面板     
  • Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  • startActivityForResult(intent, 0x1);      
  • //直接打开蓝牙       
  • adapter.enable();      
  • //关闭蓝牙       
  • adapter.disable();      
  • //打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)     
  • Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);      
  • discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)  

       3、搜索蓝牙设备

       使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备     

     请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:

       ACTION_DISCOVERY_START:开始搜索
       ACTION_DISCOVERY_FINISHED:搜索结束
       ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。

       我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能。

Java代码
  • // 创建一个接收ACTION_FOUND广播的BroadcastReceiver      
  • private final BroadcastReceiver mReceiver = new BroadcastReceiver() {      
  •     public void onReceive(Context context, Intent intent) {      
  •         String action = intent.getAction();      
  •         // 发现设备       
  •         if (BluetoothDevice.ACTION_FOUND.equals(action)) {      
  •             // 从Intent中获取设备对象       
  •             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);      
  •             // 将设备名称和地址放入array adapter,以便在ListView中显示       
  •             mArrayAdapter.add(device.getName() + "\n" + device.getAddress());        
  •         }        
  •     }        
  • };      
  •       
  • // 注册BroadcastReceiver       
  • IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);      
  • registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定     

       4、蓝牙Socket通信

       服务器端的实现

       通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)。

       调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)。

       如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket)。

Java代码
  • private class AcceptThread extends Thread {      
  •     private final BluetoothServerSocket mmServerSocket;        
  •     public AcceptThread() {      
  •         BluetoothServerSocket tmp = null;      
  •         try {                        
  •             tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);      
  •         } catch (IOException e) { }        
  •         mmServerSocket = tmp;        
  •     }      
  •     public void run() {        
  •         BluetoothSocket socket = null;                  
  •         while (true) {        
  •             try {        
  •                 socket = mmServerSocket.accept();      
  •             } catch (IOException e) {        
  •                 break;      
  •             }      
  •             if (socket != null) {      
  •                 manageConnectedSocket(socket);        
  •                 mmServerSocket.close();        
  •                 break;      
  •             }      
  •         }        
  •     }         
  •     public void cancel() {        
  •         try {        
  •             mmServerSocket.close();        
  •         } catch (IOException e) { }        
  •     }        
  • }  

       客户端的实现

       通过搜索得到服务器端的BluetoothService。

       调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)。

       调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回。

       注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败。

Java代码
  • private class ConnectThread extends Thread {   
  •     private final BluetoothSocket mmSocket;      
  •     private final BluetoothDevice mmDevice;      
  •     public ConnectThread(BluetoothDevice device) {      
  •         BluetoothSocket tmp = null;      
  •         mmDevice = device;      
  •         try {      
  •             tmp = device.createRfcommSocketToServiceRecord(MY_UUID);      
  •         } catch (IOException e) { }        
  •         mmSocket = tmp;      
  •     }      
  •    public void run() {           
  •         mBluetoothAdapter.cancelDiscovery();      
  •         try {        
  •            mmSocket.connect();        
  •         } catch (IOException connectException) {                  
  •             try {        
  •                 mmSocket.close();      
  •             } catch (IOException closeException) { }      
  •              return;      
  •         }      
  •       manageConnectedSocket(mmSocket);        
  •     }                
  •     public void cancel() {      
  •         try {        
  •             mmSocket.close();      
  •       
  •         } catch (IOException e) { }      
  •      }        
  • }   

       5、连接管理(数据通信)

       分别通过BluetoothSocket的getInputStream()和getOutputStream()方法获取InputStream和OutputStream。

       使用read(bytes[])和write(bytes[])方法分别进行读写操作。

       注意:read(bytes[])方法会一直block,知道从流中读取到信息,而write(bytes[])方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)。

Java代码
  • private class ConnectedThread extends Thread {      
  •       
  •     private final BluetoothSocket mmSocket;      
  •     private final InputStream mmInStream;      
  •     private final OutputStream mmOutStream;      
  •     public ConnectedThread(BluetoothSocket socket) {      
  •       
  •         mmSocket = socket;      
  •       
  •         InputStream tmpIn = null;      
  •       
  •         OutputStream tmpOut = null;      
  •         try {      
  •       
  •             tmpIn = socket.getInputStream();      
  •       
  •             tmpOut = socket.getOutputStream();      
  •       
  •         } catch (IOException e) { }      
  •         mmInStream = tmpIn;      
  •       
  •         mmOutStream = tmpOut;      
  •     }      
  •    public void run() {      
  •       
  •         byte[] buffer = new byte[1024];  
  •         int bytes;   
  •         while (true) {      
  •       
  •             try {      
  •                 bytes = mmInStream.read(buffer);      
  •                 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)      
  •       
  •                         .sendToTarget();      
  •       
  •             } catch (IOException e) {      
  •       
  •                 break;      
  •       
  •             }      
  •       
  •         }      
  •       
  •     }      
  •      
  •     public void write(byte[] bytes) {      
  •       
  •         try {      
  •       
  •             mmOutStream.write(bytes);      
  •       
  •         } catch (IOException e) { }      
  •       
  •     }      
  •       
  •     public void cancel() {      
  •       
  •         try {      
  •       
  •             mmSocket.close();      
  •       
  •         } catch (IOException e) { }      
  •       
  •     }      
  •       
  • }      

1 个回复

倒序浏览
我来占层楼啊  
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马