如何从主要活动中调用Android蓝牙的ConnectedThread类的write()函数

时间:2015-07-08 11:57:01

标签: java android android-bluetooth

我只想知道如何从主活动java文件中调用ConnectedThread类的write函数

public static class ConnectedThread extends Thread {
    public 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(2, bytes, -1,                                     buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    // Call this from the main activity to send data to the remote device 
    public void write(String m) {
        try {
            String msg = m;
            mmOutStream.write(msg.getBytes());
        } catch (Exception e)
            {
                e.printStackTrace();
            }

    }

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

1 个答案:

答案 0 :(得分:0)

简短的回答是你不能(也不应该)直接从Activity回调或Handler主线程中调用它。这将导致您的应用程序的主线程阻塞,因为您正在进行套接字调用。将此推迟到后台线程。您可以使用许多选项,例如HandlerThreadIntentServiceAsyncTask甚至RxJava框架。