1

所以我对java很陌生,所以要温柔。
我正在尝试通过 连接两部手机bluetooth。我创建了一个套接字,但我应该如何使用它?我的意思是,bluetooth教程说我应该打电话public void write(byte[] bytes)来发送数据,但是怎么做呢?我创建了按钮,分配了“onClick”方法,然后呢?我应该如何调用ConnectedThread形式中的方法UI thread?这是教程中的示例。

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;
        Message msg = mainHandler.obtainMessage();
        Bundle bundle = new Bundle();
        String btnTxt = "Socket aquizaired";
        bundle.putString("myKey", btnTxt);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
        // 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) { }
    }
}

UI thread我有类似的东西

private void sendSms (){   // method assigned to button "onClick"
    // i want to send some text here, like "hello" or something...
    //???????????????????????????
}
4

1 回答 1

0

android sdk 中的例子有一个非常好的蓝牙聊天例子,你应该看看。

public void write(byte[] out) {
    ConnectedThread r;
    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    r.write(out);
}
于 2013-06-19T20:08:59.343 回答