java - 如何使用类 - 蓝牙线程

标签 java android class bluetooth android-bluetooth

我正在尝试连接 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)的帮助将非常感激!

最佳答案

我不确定你模糊地理解了什么,不理解什么,但我会尽力解释这些类(class)的一般用途。

ConnectThread - 接收在发现阶段(显然是在连接之前)发现的蓝牙设备,从设备获取 BT 套接字,并且当调用 run() 时,它会尝试连接到该设备。 如果连接成功 - 在代码中它只是显示 manageConnectedSocket(mmSocket);但这意味着你应该打开一个 ConnectedThread用于通过套接字接收和发送数据。

ConnectedThread -如前所述,是管理发送和接收数据的线程。正如您在 run() 中看到的那样它不断使用 while(true) 进行监听它调用阻塞的 read - 意味着“线程被卡在那里”,直到它接收到传入的数据。 当接收到数据时,它会使用 mHandler 来处理它,这也没有在这里实现,同样,您应该只实现您想要对接收到的数据执行的任何操作。 write 方法只是接收一个字节数组并将其写入套接字,请注意,这也是一个阻塞调用,因此您应该从另一个线程使用它。

希望这能帮助你理解

关于java - 如何使用类 - 蓝牙线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211800/

相关文章:

javascript - 是否可以嵌套 JavaScript 对象?

Java将数据写入文件并下载?

java - testng - 获取包含失败测试的类的名称

android - React Native 找不到 com.android.tools.build :gradle:3. 4.2

python - 当我从 Python 中的实例而不是类继承时会发生什么?

java - 扩展类并使变量可变

java - 嵌套数据结构的对象创建,对性能的可避免影响?

java - 抛出什么异常 - "Wrong Scenario"(Java)

android - logcat 与 dmesg 之间有什么区别?

android - 如何在 Android 上更改 ImageView 的图像