蓝牙是一种支持设备短距离传输数据的无线技术。android在2.0以后提供了这方面的支持。
从查找蓝牙设备到能够相互通信要经过几个基本步骤(本机做为服务器):
1.设置权限
在manifest中配置

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



2.启动蓝牙
首先要查看本机是否支持蓝牙,获取BluetoothAdapter蓝牙适配器对象

  1. BluetoothAdaptermBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
  2. if(mBluetoothAdapter==null){
  3. //表明此手机不支持蓝牙
  4. return;
  5. }
  6. if(!mBluetoothAdapter.isEnabled()){//蓝牙未开启,则开启蓝牙
  7. IntentenableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  8. startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
  9. }
  10. //......
  11. publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  12. if(requestCode==REQUEST_ENABLE_BT){
  13. if(requestCode==RESULT_OK){
  14. //蓝牙已经开启
  15. }
  16. }
  17. }



3。发现蓝牙设备
这里可以细分为几个方面
(1)使本机蓝牙处于可见(即处于易被搜索到状态),便于其他设备发现本机蓝牙

  1. //使本机蓝牙在300秒内可被搜索
  2. privatevoidensureDiscoverable(){
  3. if(mBluetoothAdapter.getScanMode()!=
  4. BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
  5. IntentdiscoverableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  6. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
  7. startActivity(discoverableIntent);
  8. }
  9. }


(2)查找已经配对的蓝牙设备,即以前已经配对过的设备

  1. Set<BluetoothDevice>pairedDevices=mBluetoothAdapter.getBondedDevices();
  2. if(pairedDevices.size()>0){
  3. findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
  4. for(BluetoothDevicedevice:pairedDevices){
  5. //device.getName()+""+device.getAddress());
  6. }
  7. }else{
  8. mPairedDevicesArrayAdapter.add("没有找到已匹对的设备");
  9. }


(3)通过mBluetoothAdapter.startDiscovery();搜索设备,要获得此搜索的结果需要注册
一个BroadcastReceiver来获取。先注册再获取信息,然后处理

  1. //注册,当一个设备被发现时调用onReceive
  2. IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
  3. this.registerReceiver(mReceiver,filter);
  4. //当搜索结束后调用onReceive
  5. filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  6. this.registerReceiver(mReceiver,filter);
  7. //.......
  8. privateBroadcastReceivermReceiver=newBroadcastReceiver(){
  9. @Override
  10. publicvoidonReceive(Contextcontext,Intentintent){
  11. Stringaction=intent.getAction();
  12. if(BluetoothDevice.ACTION_FOUND.equals(action)){
  13. BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  14. //已经配对的则跳过
  15. if(device.getBondState()!=BluetoothDevice.BOND_BONDED){
  16. mNewDevicesArrayAdapter.add(device.getName()+"\n"+device.getAddress());//保存设备地址与名字
  17. }
  18. }elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){//搜索结束
  19. if(mNewDevicesArrayAdapter.getCount()==0){
  20. mNewDevicesArrayAdapter.add("没有搜索到设备");
  21. }
  22. }
  23. }
  24. };



4.建立连接
查找到设备 后,则需要建立本机与其他设备之间的连接。
一般用本机搜索其他蓝牙设备时,本机可以作为一个服务端,接收其他设备的连接。
启动一个服务器端的线程,死循环等待客户端的连接,这与ServerSocket极为相似。
这个线程在准备连接之前启动

  1. //UUID可以看做一个端口号
  2. privatestaticfinalUUIDMY_UUID=
  3. UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
  4. //像一个服务器一样时刻监听是否有连接建立
  5. privateclassAcceptThreadextendsThread{
  6. privateBluetoothServerSocketserverSocket;
  7. publicAcceptThread(booleansecure){
  8. BluetoothServerSockettemp=null;
  9. try{
  10. temp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
  11. NAME_INSECURE,MY_UUID);
  12. }catch(IOExceptione){
  13. Log.e("app","listen()failed",e);
  14. }
  15. serverSocket=temp;
  16. }
  17. publicvoidrun(){
  18. BluetoothSocketsocket=null;
  19. while(true){
  20. try{
  21. socket=serverSocket.accept();
  22. }catch(IOExceptione){
  23. Log.e("app","accept()failed",e);
  24. break;
  25. }
  26. }
  27. if(socket!=null){
  28. //此时可以新建一个数据交换线程,把此socket传进去
  29. }
  30. }
  31. //取消监听
  32. publicvoidcancel(){
  33. try{
  34. serverSocket.close();
  35. }catch(IOExceptione){
  36. Log.e("app","SocketType"+socketType+"close()ofserverfailed",e);
  37. }
  38. }
  39. }



搜索到设备后可以获取设备的地址,通过此地址获取一个BluetoothDeviced对象,可以看做客户端,通过此对象device.createRfcommSocketToServiceRecord(MY_UUID);同一个UUID可与服务器建立连接获取另一个socket对象,由此服务端与客户端各有一个socket对象,此时
他们可以互相交换数据了。
创立客户端socket可建立线程

  1. //另一个设备去连接本机,相当于客户端
  2. privateclassConnectThreadextendsThread{
  3. privateBluetoothSocketsocket;
  4. privateBluetoothDevicedevice;
  5. publicConnectThread(BluetoothDevicedevice,booleansecure){
  6. this.device=device;
  7. BluetoothSockettmp=null;
  8. try{
  9. tmp=device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
  10. }catch(IOExceptione){
  11. Log.e("app","create()failed",e);
  12. }
  13. }
  14. publicvoidrun(){
  15. mBluetoothAdapter.cancelDiscovery();//取消设备查找
  16. try{
  17. socket.connect();
  18. }catch(IOExceptione){
  19. try{
  20. socket.close();
  21. }catch(IOExceptione1){
  22. Log.e("app","unabletoclose()"+
  23. "socketduringconnectionfailure",e1);
  24. }
  25. connetionFailed();//连接失败
  26. return;
  27. }
  28. //此时可以新建一个数据交换线程,把此socket传进去
  29. }
  30. publicvoidcancel(){
  31. try{
  32. socket.close();
  33. }catch(IOExceptione){
  34. Log.e("app","close()ofconnectsocketfailed",e);
  35. }
  36. }
  37. }



5.建立数据通信线程,进行读取数据

  1. //建立连接后,进行数据通信的线程
  2. privateclassConnectedThreadextendsThread{
  3. privateBluetoothSocketsocket;
  4. privateInputStreaminStream;
  5. privateOutputStreamoutStream;
  6. publicConnectedThread(BluetoothSocketsocket){
  7. this.socket=socket;
  8. try{
  9. //获得输入输出流
  10. inStream=socket.getInputStream();
  11. outStream=socket.getOutputStream();
  12. }catch(IOExceptione){
  13. Log.e("app","tempsocketsnotcreated",e);
  14. }
  15. }
  16. publicvoidrun(){
  17. byte[]buff=newbyte[1024];
  18. intlen=0;
  19. //读数据需不断监听,写不需要
  20. while(true){
  21. try{
  22. len=inStream.read(buff);
  23. //把读取到的数据发送给UI进行显示
  24. Messagemsg=handler.obtainMessage(BluetoothChat.MESSAGE_READ,
  25. len,-1,buff);
  26. msg.sendToTarget();
  27. }catch(IOExceptione){
  28. Log.e("app","disconnected",e);
  29. connectionLost();//失去连接
  30. start();//重新启动服务器
  31. break;
  32. }
  33. }
  34. }
  35. publicvoidwrite(byte[]buffer){
  36. try{
  37. outStream.write(buffer);
  38. //SharethesentmessagebacktotheUIActivity
  39. handler.obtainMessage(BluetoothChat.MESSAGE_WRITE,-1,-1,buffer)
  40. .sendToTarget();
  41. }catch(IOExceptione){
  42. Log.e("app","Exceptionduringwrite",e);
  43. }
  44. }
  45. publicvoidcancel(){
  46. try{
  47. socket.close();
  48. }catch(IOExceptione){
  49. Log.e("app","close()ofconnectsocketfailed",e);
  50. }
  51. }
  52. }



到这里,蓝牙通信的基本操作已经全部完成。

更多相关文章

  1. android 获取唯一标识
  2. Android的网络状态判断
  3. Android获取设备唯一标识完美解决方案
  4. Android(安卓)Studio 3.0开始android Device Monitor弃用
  5. Android打开/关闭数据流量
  6. 重定向android log
  7. android 命令(adb shell)进入指定模拟器或设备
  8. Android(安卓)SDK自带教程之BluetoothChat
  9. 【android测试】值得学习的android测试知识连接

随机推荐

  1. 谈谈移动应用开发环境
  2. Android如何扩大按钮点击区域
  3. Android软件广告屏蔽方法及代码
  4. Android(安卓)性能优化之使用MAT分析内存
  5. Android: NDK编程入门笔记
  6. 如何使用 Eclipse 给 Android(安卓)模拟
  7. 关于android的9path图片处理
  8. windows下用ADT进行android NDK开发的详
  9. Android(安卓)之 IntentFilter 详解
  10. Android(安卓)核心分析 之七------Servic