蓝牙app开发Android开发解析

上传人:小** 文档编号:171841992 上传时间:2022-11-29 格式:DOC 页数:11 大小:42KB
收藏 版权申诉 举报 下载
蓝牙app开发Android开发解析_第1页
第1页 / 共11页
蓝牙app开发Android开发解析_第2页
第2页 / 共11页
蓝牙app开发Android开发解析_第3页
第3页 / 共11页
资源描述:

《蓝牙app开发Android开发解析》由会员分享,可在线阅读,更多相关《蓝牙app开发Android开发解析(11页珍藏版)》请在装配图网上搜索。

1、蓝牙app开发-开发解析深圳蓝牙app软件开发公司酷点网络由于近期正在开发一个通过蓝牙进行数据传递的模块,在参考了有关资料,并详细阅读了Android的官方文档后,总结了Android中蓝牙模块的使用1. 使用蓝牙的响应权限复制代码代码如下:vuses-permissionandroid:name=android.permission.BLUETOOTH/vuses-permissionandroid:name=android.permissi。n.BLUETOOTH_ADMIN/2. 配置本机蓝牙模块在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter复制代码代码如下:Blu

2、etoothAdapteradapter=BluetoothAdapter.getDefaultAdapter();直接打开系统的蓝牙设置面板Intentintent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent,0x1);直接打开蓝牙adapter.enable();关闭蓝牙adapter.disable();打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)IntentdiscoveryIntent=newIntent(BluetoothAdapter.A

3、CTION_REQUEST_DISCOVERABLE);discoverable】ntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);设置持续时间(最多300秒)3. 搜索蓝牙设备使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个SystemService中进行的,所以可以调用cancelDiscovery()方法来停止搜

4、索(该方法可以在未执行discovery请求时调用)。请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:ACTION_DISCOVERY_START:开始搜索ACTION_DISCOVERY_FINISHED:搜索结束ACTION_FOUND:找到设备,这个Intent中包含两个extrafields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能复制代码代码如下:/创建一个接收ACTION_FOUN

5、D广播的BroadcastReceiverprivatefinalBroadcastReceivermReceiver=newBroadcastReceiver()publicvoidonReceive(Contextcontext,Intentintent)Stringaction=intent.getAction();/发现设备if(BluetoothDevice.ACTION_FOUND.equals(action)/从Intent中获取设备对象BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DE

6、VICE);/将设备名称和地址放入arrayadapter,以便在Listview中显示mArrayAdapter.add(device.getName()+n+device.getAddress();/注册BroadcastReceiverIntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mReceiver,filter);/不要忘了之后解除绑定4.蓝牙Socket通信如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMMchanne

7、l下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incomingconnection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMMchannel来获取的。服务器端的实现通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String,UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)调用BluetoothServerSock

8、et的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket)复制代码代码如下:privateclassAcceptThreadextendsThreadprivatefinal

9、BluetoothServerSocketmmServerSocket;publicAcceptThread()/UseatemporaryobjectthatislaterassignedtommServerSocket,/becausemmServerSocketisfinalBluetoothServerSockettmp=null;try/MY_UUIDistheappsUUIDstring,alsousedbytheclientcodetmp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);catc

10、h(IOExceptione)mmServerSocket=tmp;publicvoidrun()BluetoothSocketsocket=null;/Keeplisteninguntilexceptionoccursorasocketisreturnedwhile(true)trysocket=mmServerSocket.accept();catch(IOExceptione)break;/Ifaconnectionwasacceptedif(socket!=null)/Doworktomanagetheconnection(inaseparatethread)manageConnect

11、edSocket(socket);mmServerSocket.close();break;/*Willcancelthelisteningsocket,andcausethethreadtofinish*/publicvoidcancel()trymmServerSocket.close();catch(IOExceptione)客户端的实现通过搜索得到服务器端的BluetoothService调用BluetoothService的listenUsingRfcommWithServiceRecord(String,UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的

12、UUID)调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败复制代码代码如下:privateclassConnectThreadextendsThreadprivatefinalBluetoothSocketmmSocket;privatefinalBluetoothDevicemmDevice;publicConnectThread(BluetoothDevice

13、device)/UseatemporaryobjectthatislaterassignedtommSocket,/becausemmSocketisfinalBluetoothSockettmp=null;mmDevice=device;/GetaBluetoothSockettoconnectwiththegivenBluetoothDevicetry/MY_UUIDistheappsUUIDstring,alsousedbytheservercodetmp=device.createRfcommSocketToServiceRecord(MY_UUID);catch(IOExceptio

14、ne)mmSocket=tmp;publicvoidrun()/CanceldiscoverybecauseitwillslowdowntheconnectionmBluetoothAdapter.cancelDiscovery();try/Connectthedevicethroughthesocket.Thiswillblock/untilitsucceedsorthrowsanexceptionmmSocket.connect();catch(IOExceptionconnectException)/Unabletoconnect;closethesocketandgetouttrymm

15、Socket.close();catch(IOExceptioncloseException)return;/Doworktomanagetheconnection(inaseparatethread)manageConnectedSocket(mmSocket);/*Willcancelanin-progressconnection,andclosethesocket*/publicvoidcancel()trymmSocket.close();catch(IOExceptione)连接管理(数据通信)分别通过BluetoothSocket的getlnputStream()和getOutpu

16、tStream()方法获取InputStream和OutputStream使用read(bytes)和write(bytes)方法分别进行读写操作注意:read(bytes)方法会一直block,知道从流中读取到信息,而write(bytes)方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)复制代码代码如下:privateclassConnectedThreadextendsThreadprivatefinalBluetoothSocketmmSocket;privatefinalInputStreammmlnStream;pr

17、ivatefinalOutputstreammmOutStream;publicConnectedThread(BluetoothSocketsocket)mmSocket=socket;InputStreamtmpIn=null;OutputStreamtmpOut=null;/Gettheinputandoutputstreams,usingtempobjectsbecause/memberstreamsarefinaltrytmpIn=socket.getInputStream();tmpOut=socket.getOutputStream();catch(IOExceptione)mm

18、InStream=tmpIn;mmOutStream=tmpOut;publicvoidrun()bytebuffer=newbyte1024;/bufferstoreforthestreamintbytes;/bytesreturnedfromread()/KeeplisteningtotheInputStreamuntilanexceptionoccurswhile(true)try/ReadfromtheInputStreambytes=mmInStream.read(buffer);/SendtheobtainedbytestotheUIActivitymHandler.obtainM

19、essage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();catch(IOExceptione)break;/*CallthisfromthemainActivitytosenddatatotheremotedevice*/publicvoidwrite(bytebytes)trymmOutStream.write(bytes);catch(IOExceptione)/*CallthisfromthemainActivitytoshutdowntheconnection*/publicvoidcancel()trymmSocket.close();catch(IOExceptione)

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!