关于android 经典蓝牙开发 使用UUID连接的问题

先贴一下我连接的代码,有点乱
开启蓝牙连接,由于连接是耗时的,所以肯定新开一个线程去连接,以下是连接的代码`package

/**
* Created by lyl on 2017/8/6.
*/

public class ConnectThread extends Thread {
private BluetoothDevice btd;
private BluetoothSocket bts;
private BluetoothController mController;
//00001101-0000-1000-8000-00805f9b34fb
public static final String MY_UUID = “00001101-0000-1000-8000-00805F9B34FB”;
private InputStream in;
private OutputStream out;
private static byte read_byts[] = new byte[120];
public static boolean isConnected = false;

public ConnectThread(BluetoothDevice btd) {
    BluetoothSocket temp = null;
    mController = new BluetoothController();
    this.btd = btd;
    try {
        temp = btd.createInsecureRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
    } catch (IOException e) {
        e.printStackTrace();
    }
    bts = temp;
}

private static android.os.Handler handler = new android.os.Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == 1) {


        }
    }
};

@Override
public void run() {
    super.run();
    //取消搜索因为搜索会让连接变慢
    mController.getmAdapter().cancelDiscovery();
    try {
        //通过socket连接设备,这是一个阻塞操作,直到连接成功或发生异常
        Log.e(TAG, "run: 连接1");
        Log.e(TAG, "当前线程2:" + Thread.currentThread());
       // bts.connect();
        bts=connectBtByChannel(btd);
        Log.e(TAG, "run: 连接2");
        Log.e(TAG, "run: 连接成功" );
        if (bts.isConnected()) {
            isConnected = true;
            in = bts.getInputStream();
            out = bts.getOutputStream();
        }
    } catch (IOException e) {
        Log.e(TAG, "run: 连接3——————————————————————》" + e.getMessage());
        Log.e(TAG, "run: 连接3");
        //无法连接,关闭socket并且退出
        System.out.println("=========拒绝");
        try {

            bts.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    while (isConnected) {
        try {
            Log.e(TAG, "当前线程:" + Thread.currentThread());
            int len = in.read(read_byts);
            if (len != -1) {
                Message me = Message.obtain();
                me.what = 1;
                handler.sendMessage(me);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //管理连接(在独立的线程)
    // manageConnectedSocket(mmSocket);
}

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
    try {
        out.write(bytes);
    } catch (IOException e) {
    }
}

public void cancel() {
    try {
        bts.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static int port = 0;

/**
 * 通过反射原理,使用随机端口发起蓝牙连接
 */
public BluetoothSocket connectBtByChannel(BluetoothDevice mBluetoothDevice) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException, InvocationTargetException {
    Method method = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
    port = port++ % 30;
    if (port == 0) {
        port = 1;
    }

    BluetoothSocket mBluetoothSocket = (BluetoothSocket) method.invoke(mBluetoothDevice, port);//1-30端口
    mBluetoothSocket.connect();//发起连接
    return mBluetoothSocket;
}

/**
 * 通过反射原理,发起蓝牙连接
 * */
public BluetoothSocket connectBtBySco(BluetoothDevice mBluetoothDevice) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException{
    Method method = mBluetoothDevice.getClass().getMethod("createScoSocket");

    BluetoothSocket mBluetoothSocket = (BluetoothSocket)method.invoke(mBluetoothDevice);
    mBluetoothSocket.connect();//发起连接
    return mBluetoothSocket;
}
/**未配对过的,在连接建立之前先配对
 * [url=home.php?mod=space&uid=2643633]@throws[/url] Exception */
public void createBond(BluetoothDevice mBluetoothDevice) throws Exception{
    try {
        // 连接建立之前的先配对
        if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
            Method creMethod = BluetoothDevice.class.getMethod("createBond");
            Log.i("BluetoothManager", "开始配对");
            creMethod.invoke(mBluetoothDevice);
        }
    } catch (Exception e) {
        // TODO: handle exception
        //DisplayMessage("无法配对!");
        e.printStackTrace();
        throw new Exception("Can't createBond with this device,please try again");
    }
}

}
一开始我是使固定的UUID去获取一个BlueToothSocket
temp = btd.createInsecureRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
拿到之后进行连接
bts.connect();
但是不知道什么原因一直返回
read failed, socket might closed or timeout, read ret: -1
可能是UUID的问题吧。
然后百度一下这个问题,也有很多人都碰到过这个问题,用了其中一个人的解决办法
地址是[http://www.eoeandroid.com/thread-913808-1-2.html?_dsign=16c362c1]得到了解决

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章