android蓝牙开发——管理连接

分类:google android应用开发 1486人阅读 评论(2) 收藏 举报 android byte buffer thread exception socket

目录(?)[+]

当你成功地连接了两台(或多台)设备时,每个设备都有一个已连接的BluetoothSocket。这时你可以在设备之间共享数据,乐趣才刚开始。 使用BluetoothSocket,传输二进制数据的过程是简单的:

  1. 分别通过getInputStream()和getOutputStream()获得管理数据传输的InputStream和OutputStream。
  2. 通过read(byte[])和write(byte[])从流中读取或写入数据。

首先,你必须使用一个线程专门用于数据的读或写。这是非常重要的,因为read(byte[])和write(byte[])方法都是阻塞调用。read(byte[])将会阻塞到流中有数据可读。write(byte[])一般不会阻塞,但当远程设备的中间缓冲区已满而对方没有及时地调用read(byte[])时将会一直阻塞。所以,你的线程中的主循环将一直用于从InputStream中读取数据。 A separate public method in the thread can be used to initiate writes to theOutputStream.

Example

[java] view plain copy
  1. privateclassConnectedThreadextendsThread{
  2. privatefinalBluetoothSocketmmSocket;
  3. privatefinalInputStreammmInStream;
  4. privatefinalOutputStreammmOutStream;
  5. publicConnectedThread(BluetoothSocketsocket){
  6. mmSocket=socket;
  7. InputStreamtmpIn=null;
  8. OutputStreamtmpOut=null;
  9. //Gettheinputandoutputstreams,usingtempobjectsbecause
  10. //memberstreamsarefinal
  11. try{
  12. tmpIn=socket.getInputStream();
  13. tmpOut=socket.getOutputStream();
  14. }catch(IOExceptione){}
  15. mmInStream=tmpIn;
  16. mmOutStream=tmpOut;
  17. }
  18. publicvoidrun(){
  19. byte[]buffer=newbyte[1024];//bufferstoreforthestream
  20. intbytes;//bytesreturnedfromread()
  21. //KeeplisteningtotheInputStreamuntilanexceptionoccurs
  22. while(true){
  23. try{
  24. //ReadfromtheInputStream
  25. bytes=mmInStream.read(buffer);
  26. //SendtheobtainedbytestotheUIActivity
  27. mHandler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
  28. }catch(IOExceptione){
  29. break;
  30. }
  31. }
  32. }
  33. /*CallthisfromthemainActivitytosenddatatotheremotedevice*/
  34. publicvoidwrite(byte[]bytes){
  35. try{
  36. mmOutStream.write(bytes);
  37. }catch(IOExceptione){}
  38. }
  39. /*CallthisfromthemainActivitytoshutdowntheconnection*/
  40. publicvoidcancel(){
  41. try{
  42. mmSocket.close();
  43. }catch(IOExceptione){}
  44. }}

更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. Android开发SQLite基本用法
  3. adb push / shell 应用替换原来的系统应用
  4. Android解析JSON方式(一)服务器端生成JSON数据
  5. android:Activity数据传递之对象(Serializable)
  6. Android(安卓)数据库的使用SQLite 和GREENDAO框架
  7. Android———利用JDBC连接服务器数据库
  8. vnc 项目的几点总结
  9. Android本地存储数据方法(超简单)

随机推荐

  1. Android(安卓)6.0 监听系统通知(Notifica
  2. android无法转换字符串到整型
  3. Windows 安装Calabash-Android
  4. Android,自定义ViewGroup实现titleBar
  5. Android(安卓)父类super.onDestroy();的
  6. 我的Android进阶之旅------>Android用Pop
  7. 【整理】Android-Recovery Mode(recover模
  8. 【Android】Handler应用(二):从服务器端加载
  9. Android(安卓)Studio 设置背景色
  10. Android(安卓)webView拦截url