1

我想在 android 中创建一个应用程序,它将连续发送位到另一个蓝牙设备。我已经完成了一切,我只是不知道如何发送位或单个字符,文本消息在接收到蓝牙设备后也会起作用,它将执行一些任务,例如打开或关闭 LED。

远程蓝牙设备是linvor bluetooth。

我目前的代码是:

 import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;


public 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(UUID.fromString("device uuid"));
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        MyService.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) { }
    }
}

现在,当我尝试初始化此类的对象时,它只会崩溃。

4

2 回答 2

0

连接套接字后,调用 mmSocket.getOutputStream()。这将获得输出流。然后就像在 Java 中的任何其他输出流一样写入它

于 2012-10-31T16:14:33.903 回答
0

正如 Gabe Sechan 所说,您将创建一个输出流,然后为输出流调用 write 方法。

private final OutputStream mmOutStream;
\\ other lines of code ...
mmOutStream = mmSocket.getOutputStream();

/**
     * Write to the connected OutStream.
     * @param buffer  The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);
            }
        catch(IOException e)
        {
            Log.e(TAG, "Exception during write", e);
        }
   }

您还可以查看安装了 Android 的蓝牙聊天示例。它位于 android-sdk\samples\android-7\BluetoothChat。这是 api 7 的版本。

希望能帮助到你。

于 2012-10-31T16:40:56.750 回答