簡體   English   中英

如何使用課程-藍牙線程

[英]How to Use Classes - Bluetooth Thread

我正在嘗試連接android和arduino並在它們之間發送數據。 我正在遵循指南http://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection

我想我模糊地理解了它是如何工作的,但是我對基礎知識沒有完全的掌握,所以我有點被卡住了。

我正在查看“作為客戶端連接”的代碼:

private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) { }
    mmSocket = tmp;
}

public void run() {
    // Cancel discovery because it will slow down the connection
    mBluetoothAdapter.cancelDiscovery();

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        try {
            mmSocket.close();
        } catch (IOException closeException) { }
        return;
    }

    // Do work to manage the connection (in a separate thread)
    manageConnectedSocket(mmSocket);
}

/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) { }
}
}

和“管理連接”

private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}

public void run() {
    byte[] buffer = new byte[1024];  // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
            // Send the obtained bytes to the UI activity
            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

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

/* Call this from the main activity to shutdown the connection */
public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) { }
}
}

我基本上復制了確切的代碼,並制作了包含它們的新Java文件。 我想實際使用這些類來發送數據,因此我將設備配對,然后找到了ID,例如:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) 
    {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) 
        {
            if (device.getName().equals("HC-06"))
            {
                //NEED TO INSERT CODE HERE (I think...)             
            }
            else
            {
                Intent intentneedsetting = new Intent(this, NeedSettingsActivity.class);       
                startActivity(intentneedsetting);
            }
        }
    }
    else
    {
        Intent intentneedsetting = new Intent(this, NeedSettingsActivity.class);       
        startActivity(intentneedsetting);
    } 

任何有關如何使用這些類(ConnectThread / ConnectedThread)的幫助將不勝感激!

我不確定您vaguley了解什么,不了解什么,但我將嘗試在總體上解釋這些類的目的。

ConnectThread接收在發現階段發現的藍牙設備(顯然在連接之前),該設備從該設備獲取BT套接字,並在調用run()時嘗試與其連接。 如果連接成功-在代碼中僅顯示manageConnectedSocket(mmSocket); 但這意味着您應該打開一個ConnectedThread以便通過套接字接收和發送數據。

ConnectedThread -如前所述,是用於管理發送和接收數據的線程。 正如您在run()看到的那樣,它會不斷地使用while(true)監聽,並調用read進行阻塞,這意味着“線程卡在了那里”,直到接收到傳入的數據為止。 接收到數據后,它將使用此處未實現的mHandler進行處理,同樣,您也應該僅執行想要對接收到的數據執行的任何操作。 write方法只是接收一個字節數組並將其寫入套接字,請注意,這也是一個阻塞調用,因此您應該從另一個線程使用它。

希望這可以幫助您理解

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM