How to call write() function of ConnectedThread class of android bluetooth from main activity

i just want to know how to call the write function of the ConnectedThread class from main activity java file

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) { }
    }
 }

Answers


The short answer is you cannot (and shouldn't) call it directly from an Activity callback or Handler tied to the main thread. This will cause the main thread of your app to block since you are making socket calls. Defer this to a background thread. There are many options you can use for this, such as HandlerThread, IntentService, AsyncTask or even the RxJava framework.


Need Your Help

Recommended Model Based Testing Tools

testing model model-driven mbt

Does anyone have any suggestions on what Model Based Testing Tools to use? Is Spec Explorer/SPEC# worth it's weight in tester training?

Android: Delete SMS at particular threadId location

android sms observer-pattern

I am trying to understand the difference between phones, and the software on them. I code and test on the Droid Incredible. A content observer of content://sms works fine and I am able to delete