Android - transfer an object via bluetooth

The Bluetooth example for Android is very useful to learn how to transfer strings between phones - is it possible to use the same code to transfer objects between phones? I have the same classes defined in both phones, I just want to transfer an instance of one class from one phone to another. Is there any sample code? I tried serializing and replacing the output stream and input stream in the chat example with objectoutputstream and objectinputstream, but it didn't seem to work

+4
source share
6 answers

The best way I found for this is as follows:

  • I set my objects as implementing Serializable, which I wanted to send.
  • I installed the following code to manage messages:

    public byte[] serialize() throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(this); return b.toByteArray(); } //AbstractMessage was actually the message type I used, but feel free to choose your own type public static AbstractMessage deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream b = new ByteArrayInputStream(bytes); ObjectInputStream o = new ObjectInputStream(b); return (AbstractMessage) o.readObject(); 
  • I changed the recording instructions to accept Serializable, and then I will make the final record:

     /** * Write to the connected OutStream. * @param buffer The bytes to write */ public void write(AbstractMessage buffer) { try { Log.v(TAG,"Writing \""+(buffer.serialize())+"\""); mmOutStream.write(buffer.serialize()); // Share the sent message back to the UI Activity mHandler.obtainMessage(AbstractMessageManager.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } 
+6
source

An example of Bluetooth Chat is a demonstration of using a serial port profile (SPP), which is based on RFCOMM. You can send any data you like sequentially after the connection is established; you just need to be able to represent your objects in a sequential stream of bytes, i.e. serialize them.

Therefore, using serialization will certainly be a way to get your objects sent by reference. The Bluetooth API send and receive functions are associated with byte arrays, but you can easily adapt the Bluetooth chat example to use streams, for example. the send function will read bytes from the stream and put them in the array buffer, then you send this buffer, etc. Then the application code will just talk through the input and output streaming channels - just as I did in the past.

So there is nothing wrong with your real idea. The big problem is that the way you implemented it is wrong, and even more problematic that the way you asked your question is also very bad. You need to describe in more detail what exactly failed, explain what kind of debugging you have already tried, as well as the Logcat code samples and output so that we can help you.

Finally, I found that, in my opinion, there was a mistake in the example of the Bluetooth Chat code: the data receiving function sends a link to the array of receiving bytes to ArrayList, which is used to display each line of the received text. This is normal when small amounts of slow text are transmitted throughout, but when you try to send large amounts of data, you start to see corrupted data, apparently because the ArrayList adapter still reads bytes from the same array, when the array is filled even more new data.

+2
source

Trev16v, First of all, thanks for your initial feedback.

To serialize my object, I used the serializeObject and deserializeObject classes from http://www.jondev.net/articles/Android_Serialization_Example_(Java ) They seem to work well: if I serialize an object (created from a class that implements Serializable) from the phone / activity and deserializes it from the same phone, I manage to get the object from the generated byte [].

Then I tried to use the same code in the BluetoothChatServices class in the bluetooth chat example in another to send the serialized object to another phone (in this example there is

  public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "create ConnectedThread"); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } 

and bytes are transmitted using

 public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } 

and read with

  public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[10240]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothManageActivity.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } 

The problem with using BluetoothChatServices is that the byte array received on the other phone is different from the one sent when it comes to serialized objects. For example, to give the idea element [0] of a serialized object = -84 when I send it, the one I receive from another phone has the element [0] - [4] = 0, then [5] = 4 and all the others items are also not aligned. I tried to write and run above in the methods to change Inputstream and Outputstream from ObjectInputStream and ObjectOutputstream, but to no avail (if this was to be implemented, I can publish the code that I tried to use)

Again, thank you very much for your help, I am new to all of these concepts, so if I say stupid things, I will also be happy to turn to the textbook

thanks

0
source

The answer is yes. A string is an object. Remember? But how exactly to do this, I'm still looking for a solution and what brought me here ...

0
source

The same problem ... When I send a series of objects from one Android device, the data is sent correctly ... But at the end of reception, all objects are not built from the received byte [].

The error occurs by accident for any received object, but the same code works correctly in Java ... I think some bytes are skipped when transferring data from one device to another ...

A serializable object for byte [] and byte [] for transforming an object can be performed using the following code

 public static byte[] toByteArray(Object obj) { byte[] bytes = null; ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(obj); oos.flush(); return bos.toByteArray(); } catch(Exception e) { Log.e("Bluetooth", "Cast exception at sending end ..."); } return bytes; } public static Object toObject(byte[] bytes) { Object obj = null; ObjectInputStream ois = null; try { ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); return ois.readObject(); } catch(Exception ex) { Log.e("Bluetooth", "Cast exception at receiving end ..."); } return obj; } 
0
source

I really found a problem - when bytes are loaded using

 try { // Read from the InputStream bytes = mmInStream.read(buffer); 

they are actually loaded in 2 stages. When debugging and entering code, I found that if it first loads 990 bytes, then the rest of the bytes. Therefore, when I return to the user interface handler, I see only the bytes loaded in the second step.

I wonder if there is a way to force loading all bytes at once

-1
source

All Articles