你好,游客 登录 注册 搜索
背景:
阅读新闻

Android蓝牙开发浅析

[日期:2012-04-23] 来源:Linux社区  作者:gd920129 [字体:大 中 小]

连接管理(数据通信)

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

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

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

  1. private class ConnectedThread extends Thread {  
  2.     private final BluetoothSocket mmSocket;  
  3.     private final InputStream mmInStream;  
  4.     private final OutputStream mmOutStream;  
  5.   
  6.     public ConnectedThread(BluetoothSocket socket) {  
  7.         mmSocket = socket;  
  8.         InputStream tmpIn = null;  
  9.         OutputStream tmpOut = null;  
  10.   
  11.         // Get the input and output streams, using temp objects because   
  12.         // member streams are final   
  13.         try {  
  14.             tmpIn = socket.getInputStream();  
  15.             tmpOut = socket.getOutputStream();  
  16.         } catch (IOException e) { }  
  17.   
  18.         mmInStream = tmpIn;  
  19.         mmOutStream = tmpOut;  
  20.     }  
  21.   
  22.     public void run() {  
  23.         byte[] buffer = new byte[1024];  // buffer store for the stream   
  24.         int bytes; // bytes returned from read()   
  25.   
  26.         // Keep listening to the InputStream until an exception occurs   
  27.         while (true) {  
  28.             try {  
  29.                 // Read from the InputStream   
  30.                 bytes = mmInStream.read(buffer);  
  31.                 // Send the obtained bytes to the UI Activity   
  32.                 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)  
  33.                         .sendToTarget();  
  34.             } catch (IOException e) {  
  35.                 break;  
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     /* Call this from the main Activity to send data to the remote device */  
  41.     public void write(byte[] bytes) {  
  42.         try {  
  43.             mmOutStream.write(bytes);  
  44.         } catch (IOException e) { }  
  45.     }  
  46.   
  47.     /* Call this from the main Activity to shutdown the connection */  
  48.     public void cancel() {  
  49.         try {  
  50.             mmSocket.close();  
  51.         } catch (IOException e) { }  
  52.     }  
  53. }  

引用资料:Android官方SDK、《Android/OPhone完全开发讲义》

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android蓝牙开发 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* 匿名 发表于 2013/5/22 17:57:31
<script>alert("ddddd");</script>