andorid蓝牙获取通信线路的基本过程

  1. private BluetoothAdapter mBluetoothAdapter = null;      
  2.       
  3. private BluetoothSocket btSocket = null;      
  4.       
  5. private OutputStream outStream = null;      
  6.       
  7. private InputStream inStream = null;      
  8.       
  9. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");  //这条是蓝牙串口通用的UUID,不要更改      
  10.       
  11. private static String address = "00:12:02:22:06:61"// <==要连接的蓝牙设备MAC地址      
  12.       
  13.       
  14. /*获得通信线路过程*/      
  15.       
  16.       
  17. /*1:获取本地BlueToothAdapter*/      
  18. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();      
  19. if(mBluetoothAdapter == null)       
  20. {      
  21.     Toast.makeText(this"Bluetooth is not available.", Toast.LENGTH_LONG).show();      
  22.     finish();      
  23.     return;      
  24. }      
  25. if(!mBluetoothAdapter.isEnabled())       
  26. {      
  27.     Toast.makeText(this"Please enable your Bluetooth and re-run this program.", Toast.LENGTH_LONG).show();      
  28.     finish();      
  29.     return;      
  30. }       
  31.        
  32. /*2:获取远程BlueToothDevice*/       
  33.     BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);      
  34. if(mBluetoothAdapter == null)       
  35. {      
  36.     Toast.makeText(this"Can't get remote device.", Toast.LENGTH_LONG).show();      
  37.     finish();      
  38.     return;      
  39. }      
  40.        
  41. /*3:获得Socket*/            
  42.     try {      
  43.     btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);      
  44. catch (IOException e) {      
  45.       
  46.     Log.e(TAG, "ON RESUME: Socket creation failed.", e);      
  47.       
  48. }      
  49.       
  50. /*4:取消discovered节省资源*/      
  51. mBluetoothAdapter.cancelDiscovery();              
  52.       
  53.       
  54. /*5:连接*/      
  55.       
  56. try {      
  57.       
  58.     btSocket.connect();      
  59.       
  60.     Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");      
  61.       
  62. catch (IOException e) {      
  63.       
  64.     try {      
  65.         btSocket.close();      
  66.       
  67.     } catch (IOException e2) {      
  68.       
  69.         Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);      
  70.     }      
  71. }       
  72.     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值