今天要做一个蓝牙4.0的通信,先做个小test,之后再看看具体的api:
@Override public void onClick(View v) { switch (v.getId()) { case R.id.scan: // bluetoothService.startBluetooth(); //1,初始化蓝牙适配器 final BluetoothManager bluetoothManager=(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter(); //2,开启蓝牙 if(bluetoothAdapter==null || !bluetoothAdapter.isEnabled()){ Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent,1); } //3,扫描附近的设备 List<Map<String,String>> deviceList=new ArrayList<>(); if(bluetoothAdapter.isDiscovering()){ bluetoothAdapter.cancelDiscovery(); }else{ //每次扫描之前都先判断一下是否存在已久配对的设备 Set<BluetoothDevice> paireDevices=bluetoothAdapter.getBondedDevices(); if(paireDevices.size()>0){ for(BluetoothDevice device :paireDevices){ Map map=new HashMap(); map.put("deviceName",device.getName()); map.put("deviceAddress",device.getAddress()); deviceList.add(map); } Log.i("扫描到的已连接设备:",deviceList.toString()); } bluetoothAdapter.startDiscovery();//开始搜索 } bluetoothAdapter.cancelDiscovery();//停止扫描 //4,通过Mac地址发送连接请求 String myMac=""; for(Map map : deviceList){ if(map.get("deviceName").toString().equals("iPhone-lhc")){ myMac=map.get("deviceAddress").toString(); } } BluetoothDevice device=bluetoothAdapter.getRemoteDevice(myMac); Log.i("我的Iphone手的地址为:",device.getAddress()); //5,通过UUID使两个设备之间建立连接 try{ BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); socket.connect();//通过socket连接服务器,这是一个阻塞的过程,直到连接建立或者连接失败 }catch(Exception exception){ Log.e("建立蓝牙连接失败:", exception.getMessage()); } break; } }
未完待续。。
时间: 2024-10-13 14:09:04