關於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]得到了解決

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