Ok, I think I know what I did wrong. Object streams are more complex, it seems that the ObjectInputStream constructor needs data to work before creating the stream. I solved this problem on
- Creating OOS.
- Run the constructor for OIS in a separate thread.
- Write some data to OOS and clear it.
- Wait for the OIS to initialize before reading from it.
This is what I am using now (note that I also added a buffer):
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 (Exception e) { Log.d(TAG,"Error in getting Input Streams"); Log.w(TAG,e); } mmInStream = tmpIn; mmOutStream = tmpOut; Log.d(TAG,"The socket is: " + mmSocket); Log.d(TAG,"The streams are: " + mmInStream + mmOutStream); Log.d(TAG,"attempting to create BufStreams"); final BufferedOutputStream bufo = new BufferedOutputStream(mmOutStream); final BufferedInputStream bufi = new BufferedInputStream(mmInStream); Log.d(TAG,"attempting to create OOS"); try { oos = new ObjectOutputStream(bufo); } catch (StreamCorruptedException e) { Log.d(TAG,"Caught Corrupted Stream Exception"); Log.w(TAG,e); } catch (IOException e) { Log.d(TAG,"Caught IOException"); Log.w(TAG,e); } Log.d(TAG,"done OOS"); if(oos==null) { Log.d(TAG,"oos is null!!!!"); } Thread s = new Thread(){ public void run(){ Log.d(TAG,"attempting to create OIS"); try { ois = new ObjectInputStream(bufi); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d(TAG,"completed OIS"); if(ois == null) { Log.d(TAG,"OIS is null"); } } }; s.start(); try { Log.d(TAG,"writing and flushing 1"); oos.write(1); oos.flush(); } catch (IOException e1) { Log.d(TAG,"CaugtIOexception"); Log.w(TAG,e1); } Log.d(TAG,"sleeping to make sure stream is set up"); while (ois == null) { try { Thread.sleep(500); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } Log.d(TAG, "done Sleeping"); // Read out the 1 to make sure everything is okay int i = 0; try { i = ois.read(); } catch (IOException e) { Log.d(TAG, "error reading"); e.printStackTrace(); } Log.d(TAG,"I received an i of: " + i); Log.d(TAG,"OO Streams set up"); } public void run() {...
Alexander
source share