1.获得蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
2.蓝牙的打开和关闭
if (!mBluetoothAdapter.isEnabled()) { new Thread(new Runnable() { @Override public void run() { mBluetoothAdapter.enable(); } }).start(); }
if (mBluetoothAdapter.isEnabled()) mBluetoothAdapter.disable();3.扫描蓝牙
if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mBluetoothAdapter.startDiscovery(); Toast.makeText(getBaseContext(), "正在搜索设备......", Toast.LENGTH_SHORT).show();
4.蓝牙状态变化都会有广播
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {//蓝牙状态改变 Log.i("ACTION_STATE_CHANGED", "----------"); setPairListView(); } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {//绑定不同设备状态改变 Log.i("BOND_STATE_CHANGED", "----------"); if (device.getBondState() == BluetoothDevice.BOND_BONDED) { //如果绑定的设备跟点击的设备名称相同,表示配对成功,保存进蓝牙路径; if (device.getName().equals(mDevice)) { mFileStore.writeBluetooth(mDevice); } //更新mPairListView和mNewListView for (String s : mNewDatas) { if (s.equals(device.getName())) { mNewDatas.remove(s); setNewListView(); setPairListView(); return; } } } setPairListView(); } else if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {//搜索到设备 Log.i("ACTION_FOUND", "----------"); newDevices.add(device); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { if (mNewDatas.size() > 0) { boolean exist = false; Log.i("aaa", "onReceive: " + mNewDatas.toString()); for (String s : mNewDatas) { if (s.equals(device.getName())) { exist = true; } } if (!exist) { mNewDatas.add(device.getName()); } } else { mNewDatas.add(device.getName()); } setNewListView(); } } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {//搜索状态改变 Log.i("DISCOVERY_STARTED", "----------"); mNewDatas.clear(); setNewListView(); }
5.绑定配对蓝牙
mDevice = mNewDatas.get(position); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } Toast.makeText(getBaseContext(), "正在配对......", Toast.LENGTH_SHORT).show(); for (BluetoothDevice device : newDevices) { if (device.getName().equals(mNewDatas.get(position))) { Log.i("mNewListView", "----------device.getName():" + device.getName()); try { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); createBondMethod.invoke(device); } catch (Exception e) { e.printStackTrace(); } return; } }
6.获得已绑定的蓝牙
pairedDevices = mBluetoothAdapter.getBondedDevices();
7.链接蓝牙()绑定蓝牙之后就是以配对蓝牙以配对蓝牙就可以链接了。)
//链接蓝牙设备 private void connectBluetooth(BluetoothDevice device) { // 固定的UUID final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID uuid = UUID.fromString(SPP_UUID); try { device.createRfcommSocketToServiceRecord(uuid).connect(); } catch (IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BluetoothActivity.this, "连接失败!", Toast.LENGTH_SHORT).show(); } }); } }
至于传统蓝牙的传输暂时没有做过,不过ble蓝牙的链接,传输数据是有做过的。晚点上传