1. 使用蓝牙的响应权限 html
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2. 打开蓝牙 android
在这里首先要了解蓝牙操做的一个核心类BluetoothAdapter,对蓝牙操做首先就须要有一个BluetoothAdapter实例。经常使用的几个方法以下: 服务器
1 // 获取本地的蓝牙适配器实例 2 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 3 if(adapter!=null) 4 { 5 if(!adapter.isEnabled()) 6 { 7 //经过这个方法来请求打开咱们的蓝牙设备 8 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 9 startActivityForResult(intent); 10 11 //不作提示,强行打开 12 //mAdapter.enable(); 13 } 14 } 15 else 16 { 17 System.out.println("本地设备驱动异常!"); 18 } 19
3.搜索蓝牙设备 app
这里能够细分为几个方面
(1)若是要使本机蓝牙可以被其余手机蓝牙发现,则经过调用startActivityForResult(Intent, int) 方法,其中,intent带有ACTION_REQUEST_DISCOVERABLE的请求。 异步
If you would like to make the local device discoverable to other devices, call startActivityForResult(Intent, int) with the ACTION_REQUEST_DISCOVERABLE action Intent.
1 //使本机蓝牙在300秒内可被搜索 2 private void ensureDiscoverable() { 3 if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { 4 //打开本机的蓝牙发现功能(默认打开120秒,能够将时间最多延长至300秒) 5 Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 6 discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒) 7 startActivity(discoverableIntent); 8 } 9 }
(2)查找已经配对的蓝牙设备,即之前已经配对过的设备 socket
1 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 2 if (pairedDevices.size() > 0) { 3 findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 4 for (BluetoothDevice device : pairedDevices) { 5 mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 6 } 7 } else { 8 mPairedDevicesArrayAdapter.add("没有找到已匹对的设备"); 9 }
(3)使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备。 this
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来获取,咱们能够本身注册相应的BroadcastReceiver来接收相应的广播,以便实现某些功能 spa
1 // 建立一个接收ACTION_FOUND广播的BroadcastReceiver 2 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 3 public void onReceive(Context context, Intent intent) { 4 String action = intent.getAction(); 5 // 发现设备 6 if (BluetoothDevice.ACTION_FOUND.equals(action)) { 7 // 从Intent中获取设备对象 8 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 9 // 将设备名称和地址放入array adapter,以便在ListView中显示 10 mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 11 } 12 } 13 }; 14 // 注册BroadcastReceiver 15 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 16 registerReceiver(mReceiver, filter); // 不要忘了以后解除绑定
4.配对 线程
配对操做呢,通常都是发现设备后,由咱们人工来进行选择后系统自动去配对。 code
5. 蓝牙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)
1 private class AcceptThread extends Thread { 2 private final BluetoothServerSocket mmServerSocket; 3 4 public AcceptThread() { 5 // Use a temporary object that is later assigned to mmServerSocket, 6 // because mmServerSocket is final 7 BluetoothServerSocket tmp = null; 8 try { 9 // MY_UUID is the app's UUID string, also used by the client code 10 tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); 11 } catch (IOException e) { } 12 mmServerSocket = tmp; 13 } 14 15 public void run() { 16 BluetoothSocket socket = null; 17 // Keep listening until exception occurs or a socket is returned 18 while (true) { 19 try { 20 socket = mmServerSocket.accept(); 21 } catch (IOException e) { 22 break; 23 } 24 // If a connection was accepted 25 if (socket != null) { 26 // Do work to manage the connection (in a separate thread) 27 manageConnectedSocket(socket); 28 mmServerSocket.close(); 29 break; 30 } 31 } 32 } 33 34 /** Will cancel the listening socket, and cause the thread to finish */ 35 public void cancel() { 36 try { 37 mmServerSocket.close(); 38 } catch (IOException e) { } 39 } 40 }
客户端的实现
经过搜索获得服务器端的BluetoothService
调用BluetoothService的createRfcommSocketToServiceRecord(UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)
调用BluetoothSocket的connect()方法(该方法为block方法),若是UUID同服务器端的UUID匹配,而且链接被服务器端accept,则connect()方法返回
注意:在调用connect()方法以前,应当肯定当前没有搜索设备,不然链接会变得很是慢而且容易失败
1 private class ConnectThread extends Thread { 2 private final BluetoothSocket mmSocket; 3 private final BluetoothDevice mmDevice; 4 5 public ConnectThread(BluetoothDevice device) { 6 // Use a temporary object that is later assigned to mmSocket, 7 // because mmSocket is final 8 BluetoothSocket tmp = null; 9 mmDevice = device; 10 11 // Get a BluetoothSocket to connect with the given BluetoothDevice 12 try { 13 // MY_UUID is the app's UUID string, also used by the server code 14 tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 15 } catch (IOException e) { } 16 mmSocket = tmp; 17 } 18 19 public void run() { 20 // Cancel discovery because it will slow down the connection 21 mBluetoothAdapter.cancelDiscovery(); 22 23 try { 24 // Connect the device through the socket. This will block 25 // until it succeeds or throws an exception 26 mmSocket.connect(); 27 } catch (IOException connectException) { 28 // Unable to connect; close the socket and get out 29 try { 30 mmSocket.close(); 31 } catch (IOException closeException) { } 32 return; 33 } 34 35 // Do work to manage the connection (in a separate thread) 36 manageConnectedSocket(mmSocket); 37 } 38 39 /** Will cancel an in-progress connection, and close the socket */ 40 public void cancel() { 41 try { 42 mmSocket.close(); 43 } catch (IOException e) { } 44 } 45 }
链接管理(数据通讯)
当你成功地链接了两台(或多台)设备时,每一个设备都有一个已链接的BluetoothSocket。这时你能够在设备之间共享数据,乐趣才刚开始。 使用BluetoothSocket,传输二进制数据的过程是简单的:
首先,你必须使用一个线程专门用于数据的读或写。这是很是重要的,由于read(byte[])和write(byte[])方法都是阻塞调用。read(byte[])将会阻塞到流中有数据可读。write(byte[])通常不会阻塞,但当远程设备的中间缓冲区已满而对方没有及时地调用read(byte[])时将会一直阻塞。因此,你的线程中的主循环将一直用于从InputStream中读取数据。
1 private class ConnectedThread extends Thread { 2 private final BluetoothSocket mmSocket; 3 private final InputStream mmInStream; 4 private final OutputStream mmOutStream; 5 6 public ConnectedThread(BluetoothSocket socket) { 7 mmSocket = socket; 8 InputStream tmpIn = null; 9 OutputStream tmpOut = null; 10 11 // Get the input and output streams, using temp objects because 12 // member streams are final 13 try { 14 tmpIn = socket.getInputStream(); 15 tmpOut = socket.getOutputStream(); 16 } catch (IOException e) { } 17 18 mmInStream = tmpIn; 19 mmOutStream = tmpOut; 20 } 21 22 public void run() { 23 byte[] buffer = new byte[1024]; // buffer store for the stream 24 int bytes; // bytes returned from read() 25 26 // Keep listening to the InputStream until an exception occurs 27 while (true) { 28 try { 29 // Read from the InputStream 30 bytes = mmInStream.read(buffer); 31 // Send the obtained bytes to the UI Activity 32 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 33 .sendToTarget(); 34 } catch (IOException e) { 35 break; 36 } 37 } 38 } 39 40 /* Call this from the main Activity to send data to the remote device */ 41 public void write(byte[] bytes) { 42 try { 43 mmOutStream.write(bytes); 44 } catch (IOException e) { } 45 } 46 47 /* Call this from the main Activity to shutdown the connection */ 48 public void cancel() { 49 try { 50 mmSocket.close(); 51 } catch (IOException e) { } 52 } 53 }