Android蓝牙通信

这里使用的是RFCOMM协议,RFCOMM是一个简单的串行线性仿真协议,此协议提供RS232控制和状态信号。

也就是一个串口(COM)传输协议,波特率为9600,8位数据。所以手机蓝牙可以与另外的蓝牙设备进行通信。

两个设备进行通信,需要建立一个服务端和一个服务端,客户端连接上服务端之后,就可以收发数据。

源代码下载地址:http://download.csdn.net/detail/menghnhhuan/3901081

 

/* 一些常量,代表服务器的名称 */
	public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";
	public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
	public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";
	public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";
	
	private BluetoothServerSocket mserverSocket = null;
	private ServerThread startServerThread = null;//开启服务线程
	private clientThread clientConnectThread = null;//客户端连接线程
	private BluetoothSocket socket = null;
	private BluetoothDevice device = null;
	private readThread mreadThread = null;//读取数据线程	
	private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//蓝牙适配器

 

开启服务端代码

startServerThread = new ServerThread();
startServerThread.start();


开启客户端

device = mBluetoothAdapter.getRemoteDevice(address);	
clientConnectThread = new clientThread();
clientConnectThread.start();


服务端代码

	//开启服务器
	private class ServerThread extends Thread { 
		public void run() {					
			try {
				/* 创建一个蓝牙服务器 
				 * 参数分别:服务器名称、UUID	 */	
				mserverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
						UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));	
				Log.d("server", "wait cilent connect...");
				
				/* 接受客户端的连接请求 */
				socket = mserverSocket.accept();
				Log.d("server", "accept success !");
				
				//启动接受数据
				mreadThread = new readThread();
				mreadThread.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};


客户端代码:

	//开启客户端
	private class clientThread extends Thread { 		
		public void run() {
			try {
				//创建一个Socket连接:只需要服务器在注册时的UUID号
				// socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);
				socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
				//连接				
				socket.connect();
				//启动接受数据
				mreadThread = new readThread();
				mreadThread.start();
			} 
			catch (IOException e) 
			{
				Log.e("connect", "", e);
				Message msg = new Message();
				msg.obj = "连接服务端异常!断开连接重新试一试。";
				msg.what = 0;
				LinkDetectedHandler.sendMessage(msg);
			} 
		}
	};

发送和接收数据代码

	//发送数据
	private void sendMessageHandle(String msg) 
	{		
		if (socket == null) 
		{
			Toast.makeText(mContext, "没有连接", Toast.LENGTH_SHORT).show();
			return;
		}
		try {				
			OutputStream os = socket.getOutputStream(); 
			os.write(msg.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
	//读取数据
    private class readThread extends Thread { 
        public void run() {
        	
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream mmInStream = null;
            
			try {
				mmInStream = socket.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



 

你可能感兴趣的:(android)