Android实现蓝牙远程连接遇到的问题
主要问到的问题:1.uuid获取不到,一直为空,后来发现android4.2之前使用uuid这种方法,目前尽量不使用uuid方式
2.socket.connect()出错,报read failed, socket might closed or timeout, read ret: -1;这个错,解觉方法就是另开一个子线程 专门执行socket.connect()方法
源码:
package com.example.testopencv.client; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.Intent; import android.os.ParcelUuid; import android.util.Log; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.UUID; public class ConnThread extends Thread { private BluetoothDevice device; private BluetoothSocket socket; private Context mContext; public ConnThread(BluetoothDevice device) { this.device = device; System.out.println(device.getBluetoothClass()+"这里要连接"); // UUID uuid = device.getUuids()[0].getUuid(); //System.out.println(uuid+"这是uuid"); try { socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { //java.io.IOException: Service discovery failed // 连接蓝牙服务端 socket.connect(); // 发送内容 socket.getOutputStream().write(new String("Hello").getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
效果:


参考文章:蓝牙通信的坑,read failed, socket might closed or timeout, read ret: -1_bobo丶仔_新浪博客 (sina.com.cn)

浙公网安备 33010602011771号