android设备终端与蓝牙模块(HC-06)的通讯编程思路

来源:互联网 发布:wow数据库黑翼之巢 编辑:程序博客网 时间:2024/05/09 23:18

蓝牙模块(HC-06):



在这个项目中,手机端作为客户端,去连接到蓝牙模块上。而接受蓝牙模块发过来的信息的时候,是没有必要再创建服务器端的,我们只要一个不断监听对方消息的循环就行。

 

注意:在socket.connect();之前,我们需要执行bluetoothadapter.canceldiscovery();,这是为了停掉搜索设备,否则连接可能会变得非常慢,并且容易失败。

 

蓝牙开发中的几个关键步骤:

1、开启手机上的蓝牙功能。

2、搜索附近存在的蓝牙设备。

3、创建蓝牙socket,由socket获取device

4、发送和读取数据。

5、清场(断开各种线程,注销广播接收器等)

 

//主线条

Adapter  ---->   device  ----->  socket

 

/* step1:取得默认的蓝牙适配器 */

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();  

//step2:强制开启蓝牙设备

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. if(!mBtAdapter.isEnabled()){  
  2. mBtAdapter.enable();  
  3. }  


//step3:注册广播接收器,注意:开启step4即搜索设备前,应先注册广播接收器

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. reg_broadcastreceiver();  
  2.    
  3. private void reg_broadcastreceiver(){  
  4.  //Register for broadcasts when a device is discovered  
  5.         IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  6.         this.registerReceiver(mReceiver, discoveryFilter);  
  7.         //System.out.println("***********" + mBtAddress);  
  8.         //Register for broadcasts when discovery has finished  
  9.         IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  10.         this.registerReceiver(mReceiver, foundFilter);  
  11. }  
  12.    
  13.     
  14.     // The BroadcastReceiver that listens for discovered devices and  
  15.     // changes the title when discovery is finished  
  16.     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  17.         @Override  
  18.         public void onReceive(Context context, Intent intent) {  
  19.             String action = intent.getAction();  
  20.             // When discovery finds a device  
  21.             if (BluetoothDevice.ACTION_FOUND.equals(action))   
  22.             {  
  23.                 // Get the BluetoothDevice object from the Intent  
  24.                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  25.                   
  26.                 Log.d("BroadcastReceiver""find device:"+device.getName()+"|"+device.getAddress());  
  27.                 mBtAddress = device.getAddress();    
  28.                                   
  29.              <span style="background-color: rgb(255, 255, 0);">//step5:根据搜索到的蓝牙设备的MAC地址,得到该设备</span>  
  30.              mBtDevice = mBtAdapter.getRemoteDevice(mBtAddress);  
  31.              <span style="background-color: rgb(255, 255, 0);">//step6:开启客户端线程,线程里面完成了与SPP协议的连接 </span>  
  32.              mBtClientConnectThread = new clientThread();  
  33.              mBtClientConnectThread.start();  
  34.           
  35.           
  36.              
  37.             }  // When discovery is finished, change the Activity title  
  38.             else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))   
  39.             {  
  40.                setTitle("搜索完成");  
  41.                  
  42.                Log.d("BroadcastReceiver""find over");  
  43.             }  
  44.             
  45.              
  46.         }  
  47.     };  
  48.    


//step4: 开始搜索附近可以存在的蓝牙设备,之后系统会发送广播给广播接收器

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. mBtAdapter.startDiscovery();  


//附加客户端线程 代码

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //客户端线程   
  2. private class clientThread extends Thread{  
  3.     public void run(){  
  4.         Log.d("mBtSocket""start-->"+mBtSocket);  
  5.         try {  
  6. /step7,取消搜索设备的动作,否则接下来的设备连接会失败  
  7.             mBtAdapter.cancelDiscovery();  
  8. /step8,根据device获取socket  
  9.             mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
  10. /step9,连接socket  
  11.             mBtSocket.connect();  
  12.         } catch (IOException e) {  
  13.             // TODO Auto-generated catch block  
  14.             e.printStackTrace();  
  15.             Log.e("connect""", e);  
  16.             Log.d("clientThread""连接失败");  
  17.               
  18.         }  
  19.         Log.d("mBtSocket""end-->"+mBtSocket);  
  20.     }  
  21. }  



//step10,发送数据.

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. sendMessageHandle(“要发送的数据”);  

//step10, 读取数据

(由于接收数据的线程已经打开,所以当有数据到来时,数据就自动赋给变量S了,而此时S就是我们读取的数据 )


//step11,清场(清场动作放在ondestroy里面)

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @Override  
  2.     protected void onDestroy() {  
  3.         // TODO Auto-generated method stub  
  4.         super.onDestroy();  
  5.           
  6.         //关闭客户端进程,取消广播接收器  
  7.         shutdownClient();  
  8.         // Unregister broadcast listeners  
  9.         this.unregisterReceiver(mReceiver);  
  10.         //关闭读线程   
  11.         if(mReadThread != null)  
  12.         {  
  13.             mReadThread.interrupt();  
  14.             mReadThread = null;  
  15.         }                 
  16.     }  
  17.   
  18.   
  19. /* 停止客户端连接 */  
  20.     private void shutdownClient() {  
  21.         new Thread() {  
  22.             public void run() {  
  23.                 if(mBtClientConnectThread!=null)  
  24.                 {  
  25.                     mBtClientConnectThread.interrupt();  
  26.                     mBtClientConnectThread= null;  
  27.                 }  
  28.                 if (mBtSocket != null) {  
  29.                     try {  
  30.                         mBtSocket.close();  
  31.                     } catch (IOException e) {  
  32.                         // TODO Auto-generated catch block  
  33.                         e.printStackTrace();  
  34.                     }  
  35.                     mBtSocket = null;  
  36.                 }  
  37.             };  
  38.         }.start();  
  39.     }  
  40.   
  41.   
  42.   
  43.     //发送数据  
  44.     public static void sendMessageHandle(String msg)   
  45.     {         
  46.         if (mBtSocket == null)    
  47.         {  
  48.             Log.d("----------------------""没有连接");  
  49.             return;  
  50.         }  
  51.           
  52.         try {  
  53.             OutputStream os = mBtSocket.getOutputStream();   
  54.             os.write(msg.getBytes()); //发送出去的值为:msg  
  55.         } catch (IOException e) {  
  56.             // TODO Auto-generated catch block  
  57.             e.printStackTrace();  
  58.         }             
  59.     }  




附:发送数据和读取数据的代码
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //发送数据  
  2.     public static void sendMessageHandle(String msg)   
  3.     {         
  4.         if (mBtSocket == null)    
  5.         {  
  6.             Log.d("----------------------""没有连接");  
  7.             return;  
  8.         }  
  9.           
  10.         try {  
  11.             OutputStream os = mBtSocket.getOutputStream();   
  12.             os.write(msg.getBytes()); //发送出去的值为:msg  
  13.         } catch (IOException e) {  
  14.             // TODO Auto-generated catch block  
  15.             e.printStackTrace();  
  16.         }             
  17.     }  
  18.       
  19.     //读取数据  
  20.     private static class readThread extends Thread {   
  21.         public void run() {  
  22.               
  23.             byte[] buffer = new byte[1024];  
  24.             int bytes;  
  25.             InputStream mmInStream = null;  
  26.               
  27.             try {  
  28.                 mmInStream = mBtSocket.getInputStream();  
  29.             } catch (IOException e1) {  
  30.                 // TODO Auto-generated catch block  
  31.                 e1.printStackTrace();  
  32.             }     
  33.             while (true) {  
  34.                 try {  
  35.                     // Read from the InputStream  
  36.                     if( (bytes = mmInStream.read(buffer)) > 0 )  
  37.                     {  
  38.                         byte[] buf_data = new byte[bytes];  
  39.                         for(int i=0; i<bytes; i++)  
  40.                         {  
  41.                             buf_data[i] = buffer[i];  
  42.                         }  
  43.                         String s = new String(buf_data);//接收的值inputstream 为 s  
  44.                           
  45.                         if(s.equalsIgnoreCase("o")){ //o表示opend!  
  46.                             isClosed = false;  
  47.                         }  
  48.                         else if(s.equalsIgnoreCase("c")){  //c表示closed!  
  49.                             isClosed = true;                          
  50.                         }  
  51.                           
  52.                           
  53.                     }  
  54.                 } catch (IOException e) {  
  55.                     try {  
  56.                         mmInStream.close();  
  57.                     } catch (IOException e1) {  
  58.                         // TODO Auto-generated catch block  
  59.                         e1.printStackTrace();  
  60.                     }  
  61.                     break;  
  62.                 }  
  63.             }  
  64.         }  
  65.     }  

0 0