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

蓝牙模块(HC-06):



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

 

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

 

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

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

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

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

4、发送和读取数据。

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

 

//主线条

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

 

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

private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

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

if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}


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

reg_broadcastreceiver();
 
private void reg_broadcastreceiver(){
 //Register for broadcasts when a device is discovered
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, discoveryFilter);
        //System.out.println("***********" + mBtAddress);
        //Register for broadcasts when discovery has finished
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, foundFilter);
}
 
  
    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                
            	Log.d("BroadcastReceiver", "find device:"+device.getName()+"|"+device.getAddress());
                mBtAddress = device.getAddress();  
                                
        	 //step5:根据搜索到的蓝牙设备的MAC地址,得到该设备
        	 mBtDevice = mBtAdapter.getRemoteDevice(mBtAddress);
        	 //step6:开启客户端线程,线程里面完成了与SPP协议的连接 
        	 mBtClientConnectThread = new clientThread();
        	 mBtClientConnectThread.start();
        
        
           
            }  // When discovery is finished, change the Activity title
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
            {
               setTitle("搜索完成");
               
               Log.d("BroadcastReceiver", "find over");
            }
          
           
        }
    };
 


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

mBtAdapter.startDiscovery();


//附加客户端线程 代码

 //客户端线程 
	private class clientThread extends Thread{
		public void run(){
			Log.d("mBtSocket", "start-->"+mBtSocket);
			try {
//step7,取消搜索设备的动作,否则接下来的设备连接会失败
				mBtAdapter.cancelDiscovery();
//step8,根据device获取socket
				mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//step9,连接socket
				mBtSocket.connect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e("connect", "", e);
				Log.d("clientThread", "连接失败");
				
			}
			Log.d("mBtSocket", "end-->"+mBtSocket);
		}
	}



//step10,发送数据.

sendMessageHandle(“要发送的数据”);

//step10, 读取数据

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


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

@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		//关闭客户端进程,取消广播接收器
    	shutdownClient();
        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
        //关闭读线程 
		if(mReadThread != null)
		{
			mReadThread.interrupt();
			mReadThread = null;
		}				
	}


/* 停止客户端连接 */
	private void shutdownClient() {
		new Thread() {
			public void run() {
				if(mBtClientConnectThread!=null)
				{
					mBtClientConnectThread.interrupt();
					mBtClientConnectThread= null;
				}
				if (mBtSocket != null) {
					try {
						mBtSocket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mBtSocket = null;
				}
			};
		}.start();
	}



	//发送数据
	public static void sendMessageHandle(String msg) 
	{		
		if (mBtSocket == null)  
		{
			Log.d("----------------------", "没有连接");
			return;
		}
		
		try {
			OutputStream os = mBtSocket.getOutputStream(); 
			os.write(msg.getBytes()); //发送出去的值为:msg
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}




附:发送数据和读取数据的代码
//发送数据
	public static void sendMessageHandle(String msg) 
	{		
		if (mBtSocket == null)  
		{
			Log.d("----------------------", "没有连接");
			return;
		}
		
		try {
			OutputStream os = mBtSocket.getOutputStream(); 
			os.write(msg.getBytes()); //发送出去的值为:msg
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
	
	//读取数据
    private static class readThread extends Thread { 
        public void run() {
        	
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream mmInStream = null;
            
			try {
				mmInStream = mBtSocket.getInputStream();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
            while (true) {
                try {
                    // Read from the InputStream
                    if( (bytes = mmInStream.read(buffer)) > 0 )
                    {
	                    byte[] buf_data = new byte[bytes];
				    	for(int i=0; i<bytes; i++)
				    	{
				    		buf_data[i] = buffer[i];
				    	}
						String s = new String(buf_data);//接收的值inputstream 为 s
						
						if(s.equalsIgnoreCase("o")){ //o表示opend!
							isClosed = false;
						}
						else if(s.equalsIgnoreCase("c")){  //c表示closed!
							isClosed = true;						
						}
						
						
                    }
                } catch (IOException e) {
                	try {
						mmInStream.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
                    break;
                }
            }
        }
    }


没有更多推荐了,返回首页