1. 使用蓝牙的响应权限

<strong><uses-permissionandroid:name="android.permission.BLUETOOTH"/><uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/></strong>


2. 配置本机蓝牙模块

在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter

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

3.搜索蓝牙设备

使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备

startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。

请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:

ACTION_DISCOVERY_START:开始搜索

ACTION_DISCOVERY_FINISHED:搜索结束

ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。

我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能

//创建一个接收ACTION_FOUND广播的BroadcastReceiverprivatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){publicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();//发现设备if(BluetoothDevice.ACTION_FOUND.equals(action)){//从Intent中获取设备对象BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//将设备名称和地址放入arrayadapter,以便在ListView中显示mArrayAdapter.add(device.getName()+"\n"+device.getAddress());}}};//注册BroadcastReceiverIntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mReceiver,filter);//不要忘了之后解除绑定


4. 蓝牙Socket通信

如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。

服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incoming connection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMM channel来获取的。

服务器端的实现

通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)

调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)

如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket

privateclassAcceptThreadextendsThread{privatefinalBluetoothServerSocketmmServerSocket;publicAcceptThread(){//UseatemporaryobjectthatislaterassignedtommServerSocket,//becausemmServerSocketisfinalBluetoothServerSockettmp=null;try{//MY_UUIDistheapp'sUUIDstring,alsousedbytheclientcodetmp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);}catch(IOExceptione){}mmServerSocket=tmp;}publicvoidrun(){BluetoothSocketsocket=null;//Keeplisteninguntilexceptionoccursorasocketisreturnedwhile(true){try{socket=mmServerSocket.accept();}catch(IOExceptione){break;}//Ifaconnectionwasacceptedif(socket!=null){//Doworktomanagetheconnection(inaseparatethread)manageConnectedSocket(socket);mmServerSocket.close();break;}}}/**Willcancelthelisteningsocket,andcausethethreadtofinish*/publicvoidcancel(){try{mmServerSocket.close();}catch(IOExceptione){}}}

客户端的实现


通过搜索得到服务器端的BluetoothService

调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)

调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回

注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败

privateclassConnectThreadextendsThread{privatefinalBluetoothSocketmmSocket;privatefinalBluetoothDevicemmDevice;publicConnectThread(BluetoothDevicedevice){//UseatemporaryobjectthatislaterassignedtommSocket,//becausemmSocketisfinalBluetoothSockettmp=null;mmDevice=device;//GetaBluetoothSockettoconnectwiththegivenBluetoothDevicetry{//MY_UUIDistheapp'sUUIDstring,alsousedbytheservercodetmp=device.createRfcommSocketToServiceRecord(MY_UUID);}catch(IOExceptione){}mmSocket=tmp;}publicvoidrun(){//CanceldiscoverybecauseitwillslowdowntheconnectionmBluetoothAdapter.cancelDiscovery();try{//Connectthedevicethroughthesocket.Thiswillblock//untilitsucceedsorthrowsanexceptionmmSocket.connect();}catch(IOExceptionconnectException){//Unabletoconnect;closethesocketandgetouttry{mmSocket.close();}catch(IOExceptioncloseException){}return;}//Doworktomanagetheconnection(inaseparatethread)manageConnectedSocket(mmSocket);}/**Willcancelanin-progressconnection,andclosethesocket*/publicvoidcancel(){try{mmSocket.close();}catch(IOExceptione){}}}</strong>

连接管理(数据通信)


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

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

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

<strong>privateclassConnectedThreadextendsThread{privatefinalBluetoothSocketmmSocket;privatefinalInputStreammmInStream;privatefinalOutputStreammmOutStream;publicConnectedThread(BluetoothSocketsocket){mmSocket=socket;InputStreamtmpIn=null;OutputStreamtmpOut=null;//Gettheinputandoutputstreams,usingtempobjectsbecause//memberstreamsarefinaltry{tmpIn=socket.getInputStream();tmpOut=socket.getOutputStream();}catch(IOExceptione){}mmInStream=tmpIn;mmOutStream=tmpOut;}publicvoidrun(){byte[]buffer=newbyte[1024];//bufferstoreforthestreamintbytes;//bytesreturnedfromread()//KeeplisteningtotheInputStreamuntilanexceptionoccurswhile(true){try{//ReadfromtheInputStreambytes=mmInStream.read(buffer);//SendtheobtainedbytestotheUIActivitymHandler.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){}}}</strong>

转自:http://blog.csdn.net/gd920129/article/details/7487761


更多相关文章

  1. 安卓巴士自测试题-第二期
  2. Android--launcher启动过程解析
  3. android8.1 系统应用使用FileProvider时提示没有权限
  4. Android使用post方式上传图片到服务器的方法
  5. Android点击button触发Toast事件,弹出一个小小的消息框,几秒钟之
  6. INSTALL_FAILED_TEST_ONLY
  7. android phone application 通知missed call的过程
  8. Android(安卓)关于倒计时功能的实现
  9. Android:activity,fragment和service之我见(准备更新)

随机推荐

  1. MySQL实例crash的案例详细分析
  2. mysql5.6.zip格式压缩版安装图文教程
  3. mysql 5.6 压缩包版安装方法
  4. 浅谈mysql使用limit分页优化方案的实现
  5. MySQL对于各种锁的概念理解
  6. Mysql多主一从数据备份的方法教程
  7. 分析Mysql表读写、索引等操作的sql语句效
  8. Mysql:The user specified as a definer
  9. Android实现图标水印
  10. Word文档的读取,WordToHtml(Android)