在主UI线程中实现runnable的类的方法上设置计时器

时间:2015-04-16 21:07:18

标签: java android multithreading runnable

我是android的绝对初学者。目前,我正在尝试制作一个应用程序,通过蓝牙将输出数据发送到arduino。为此,我创建了一个类如下。

private class SendReceiveBytes implements Runnable {
    private BluetoothSocket btSocket;
    private InputStream inputStream;
    private OutputStream outputStream;
    String TAG = "SendReceiveBytes";

    public SendReceiveBytes(BluetoothSocket socket) {
        btSocket = socket;
        try {
            inputStream = btSocket.getInputStream();
            outputStream = btSocket.getOutputStream();
        }
        catch (IOException streamError) {
            Log.e(TAG, "Error when getting input or output Stream");
        }
    }

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

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

    /* Call this from the main activity to send data to the remote device */
    public void write(String outputData) {
        try {
            outputStream.write(outputData.getBytes(Charset.forName("UTF-8")));
        }
        catch (IOException e) {
            Log.e(TAG, "Error when writing to outputStream");
        }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            btSocket.close();
        }
        catch (IOException e) {
            Log.e(TAG, "Error when closing the btSocket");
        }
    }
}

在我的OnCreate()方法中,我的操作如下。

final SendReceiveBytes sendBytes = new SendReceiveBytes(bluetoothSocket);
final Handler moveHandler = new Handler();
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            switch (view.getId()) {
                case R.id.driveFwd:
                    moveHandler.postDelayed(sendBytes.write("MOVE_FORWARD"), 250);
                    sendBytes.write("MOVE_FORWARD");
                    break;

我目前遇到的问题是使用正确的调用方法write()的过程。什么是继续下去的正确方法?

1 个答案:

答案 0 :(得分:0)

看看连接到arduino的这个类。我刚才写过这篇文章。问题是,如果你不知道android在这里开始是非常困难的。 看看BluetoothHandlerClass

https://github.com/rush2sk8/BluetoothHandler