Cannot create ObjectInputStream with InputStream for a Bluetooth Socket on the Android Platform

Alexander picture Alexander · Apr 9, 2011 · Viewed 7.2k times · Source

I am writing a multiplayer game for Android phones. Communication is via Bluetooth. I have managed to send bytes from one phone to the other using the input / output stream. Since I need to be able to transfer objects I want objectstreams. However, when I try to create an Objectstream with my streams, my program hangs on the instruction.

public class ConnectedThread extends Thread {
private static final String TAG = "Connected Thread";
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Handler mHandler;
private ObjectInputStream ois;
private ObjectOutputStream oos;

public ConnectedThread(BluetoothSocket socket,Handler h) {
    mmSocket = socket;
    mHandler = h;

    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;
    Log.d(TAG,"attempting to create OIS");

    try {
    ois = new ObjectInputStream(mmInStream);

// The instruction new ObjectInputStream(mmInStream) NEVER FINISHES EXECUTING. It doesn't seem to throw an error, because I'd catch it. It just hangs at this instruction. None of the code below this line is ever executed.

    } catch (Exception e) {

        Log.e(TAG,"Error");
        Log.d(TAG,e.getMessage());
        e.printStackTrace();
    } 

    Log.d(TAG,"attempting to create OOS");
    try {
        oos = new ObjectOutputStream(mmOutStream);
    } catch (IOException e) {
        Log.e(TAG,"IO exception for Output Stream, I have no idea what caused this");
        Log.d(TAG,e.getMessage());
    }

}

public void run() {.....}

What am I doing wrong?

Answer

user207421 picture user207421 · Apr 16, 2011

Just construct the ObjectOutputStream, and flush() it, at both ends before constructing the ObjectInputStream. You don't have to write any data of your own.