android bluetooth开发基础-9管理连接
16lz
2021-01-26
android蓝牙开发——管理连接
分类:google android应用开发 2010-08-11 23:17 1486人阅读 评论(2) 收藏 举报 android byte buffer thread exception socket目录(?)[+]
当你成功地连接了两台(或多台)设备时,每个设备都有一个已连接的BluetoothSocket。这时你可以在设备之间共享数据,乐趣才刚开始。 使用BluetoothSocket,传输二进制数据的过程是简单的:
- 分别通过getInputStream()和getOutputStream()获得管理数据传输的InputStream和OutputStream。
- 通过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- privateclassConnectedThreadextendsThread{
- privatefinalBluetoothSocketmmSocket;
- privatefinalInputStreammmInStream;
- privatefinalOutputStreammmOutStream;
- publicConnectedThread(BluetoothSocketsocket){
- mmSocket=socket;
- InputStreamtmpIn=null;
- OutputStreamtmpOut=null;
- //Gettheinputandoutputstreams,usingtempobjectsbecause
- //memberstreamsarefinal
- try{
- tmpIn=socket.getInputStream();
- tmpOut=socket.getOutputStream();
- }catch(IOExceptione){}
- mmInStream=tmpIn;
- mmOutStream=tmpOut;
- }
- publicvoidrun(){
- byte[]buffer=newbyte[1024];//bufferstoreforthestream
- intbytes;//bytesreturnedfromread()
- //KeeplisteningtotheInputStreamuntilanexceptionoccurs
- while(true){
- try{
- //ReadfromtheInputStream
- bytes=mmInStream.read(buffer);
- //SendtheobtainedbytestotheUIActivity
- mHandler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
- }catch(IOExceptione){
- break;
- }
- }
- }
- /*CallthisfromthemainActivitytosenddatatotheremotedevice*/
- publicvoidwrite(byte[]bytes){
- try{
- mmOutStream.write(bytes);
- }catch(IOExceptione){}
- }
- /*CallthisfromthemainActivitytoshutdowntheconnection*/
- publicvoidcancel(){
- try{
- mmSocket.close();
- }catch(IOExceptione){}
- }}
更多相关文章
- 一句话锁定MySQL数据占用元凶
- Android开发SQLite基本用法
- adb push / shell 应用替换原来的系统应用
- Android解析JSON方式(一)服务器端生成JSON数据
- android:Activity数据传递之对象(Serializable)
- Android(安卓)数据库的使用SQLite 和GREENDAO框架
- Android———利用JDBC连接服务器数据库
- vnc 项目的几点总结
- Android本地存储数据方法(超简单)