Bluetooth getInputStream gets multiple/splitted Datapackages? - android

i'm using the Infamous BluetoothChat-Example from Google to receive a ByteArray.
I know his length (55bytes), his Start Byte (0x69) and his End Byte (0x16) as well as the length of the data in the Array.
I'm quite sure that the Sender sends out 55 Bytes without any interruption but on the BluethootChat Example it looks like i receive multiple data packages.
The first package consists of 0x69 followed by 1023 times 0x00.
Then i receive the rest of the 55bytes.
This happens 70% of the time, sometimes the array get spiltted in the middle and sometimes the whole array is received complete.
Is this a normal Android-Bluetooth behavior
Thanks in advance...
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
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;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
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(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}

This answer here answered the same question. I just had a same issue and this answer was what I found.

Related

bluetooth InputStream in android gets corrupted after sending with OutputStream

So, I am using my arduino to collect some data and send it to my android app , so that I can store this data in a file, making my android a sort of datalogger.
I am using an hC-06 for this, working at 115200 bauds/sec. Seems to be allright when the arduino sends the data chunks ( 60bytes every chunk) every 100ms aprox.
The problem begins when I "query" the arduino for some special data, by sending a single byte with the OutputStream method. From the moment the app uses the "mmOutStream.write(buffer);" the data received by InputStream becomes unstable, varying the chunk size with random values ( 60 bytes, 45 butes, 100 bytes, etc...)
It seems like using OutputStream kind of corrupts the InputStream buffer...
Anyone has been through this? Thaks in advance
below the code:
// It handles all incoming and outgoing transmissions.
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean send_request=false;
private byte[] send_buffer;
public ConnectedThread(BluetoothSocket socket, String socketType) {
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) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer;
ArrayList<Integer> arr_byte = new ArrayList<Integer>();
// Keep listening to the InputStream while connected
while (true) {
try {
int data = mmInStream.read();
if(data == 0x0A) {
}
else if(data == 0x0D) {
buffer = new byte[arr_byte.size()];
for(int i = 0 ; i < arr_byte.size() ; i++) {
buffer[i] = arr_byte.get(i).byteValue();
}
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothState.MESSAGE_READ
, buffer.length, -1, buffer).sendToTarget();
arr_byte = new ArrayList<Integer>();
}
else {
arr_byte.add(data);
}
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
BluetoothService.this.start(BluetoothService.this.isAndroid);
break;
}
}
}
// Write to the connected OutStream.
// #param buffer The bytes to write
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// mmOutStream.close(); //vdv , close after writing to see if liberates memeory . uncommenting this causes the phone not to connect
//TODO: investigate and solve why a single writing in the outstream causes the inputstream to get corrupted after a while.
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothState.MESSAGE_WRITE
, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.d(TAG,"write exception"); //vdv
}
}

Read Bluetooth Message in External android app

I'am a newbie to android Bluetooth and I want to read and store the Bluetooth message in external android app(mine) using internal storage or sqlite. I have tried the android bluetooth-chat sample from GitHub but I don't know how to implement my idea.
Any help would be helpful and thanks
Exchange of bluetooth messages is covered in the android.bluetooth section of the api.
http://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection
Here is a basic example of managing a connection and sending/receiving messages:
private class ConnectedThread extends Thread {
private 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(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}

Bluetooth - Receive data from multiple device in same time on android

I'm trying to receive data from multiple device in same time, i'm using createInsecureRfcommSocketToServiceRecord() and the SPP UUID 00001101-0000-1000-8000-00805F9B34FB to connect to non-android devices.
So i'm running 3 instance of ConnectedThread, i'm able to write to all device, but i can't receive from 2 device at same time.
Example : i'm connecting to 2 Pc using HyperTerminal, if i send a txt file on both at the same time, i will receive only one on my android device, the other one is ignored.
I'm looking this library : http://arissa34.github.io/Android-Multi-Bluetooth-Library/ seems i have to run a server on my android phone.
How can I achieve this?
Best regards.
private class ConnectedThread extends Thread {
private 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(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}

How to serialize an object and then send it over bluetooth

I'm making a Battleships game and I want to send an Array of a class named Ships(which contains stuff like ship name, size, rotated or not and an arraylist for coordinates). I've googled this and looked on Stack overflow and I basically need to serialize the array, but this is where I'm stuck. I need to use ObjectOutputStream, but how do I encorporate that into the code below (taken from android dev site). Note I have already made the ship class implement serializable. Thanks in advance
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "connectedthread started");
// mHandler.obtainMessage(TEST).sendToTarget();
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) {
Log.e(TAG, "temp sockets not created");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "Begin mConnectedThread");
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
Log.i(TAG, "reaaaad msg");
mHandler.obtainMessage(SetUpGame.MESSAGE_READ2, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnectd");
break;
}
}
}
/*
* Call this from the main activity to send data to the remote
* device
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
Log.i(TAG, "writeeee msg");
mHandler.obtainMessage(SetUpGame.MESSAGE_WRITE, -1,-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close of connect socket failed");
}
}
}
and my handler:
final Handler mHandler = new Handler() {
#Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MESSAGE_READ2:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
//Toast.makeText(getApplicationContext(),"Me:" + writeMessage, Toast.LENGTH_SHORT).show();
break;
In the code above you get input/output streams from the connected socket.
Now you can stream data to/from the socket using those streams.
How exactly you do this depends on the type of data you want to stream. In this case you have a serializable Object to send, so you will wrap your stream in a filter that adapts the stream for use with Objects: ObjectOutputStream/ObjectInputStream...
ObjectOutputStream oos = new ObjectOutputStream( mmOutStream );
for (Ship ship: ships)
oos.writeObject( ship );
This code iterates through the array of Ships, writing each ship to the stream (and hence, to the Bluetooth socket).
The receiving side is the same, with one additional complication: you don't necessarily know when to stop or what to read. There are various schemes for handling this, and there are SO questions dealing specifically with this. The Bluetooth page of the Android developer's guide has sample code for this:
http://developer.android.com/guide/topics/connectivity/bluetooth.html

How to connect a bluetooth adapter with Object Push Protocol?

I saw in Android 2.1 highlight it said new platform support: "Bluetooth 2.1, New BT profiles: Object Push Profile (OPP) and Phone Book Access Profile (PBAP)". Now I have bluetooth adpater with OPP support. I can search and pair with it. But how can I get the txt file it send to me. There is no API for this function. I'm using the BluetoothChat sample code like structure as below. But the code is block in
"bytes = mmInStream.read(buffer);".
And nothing happens. Why? Nothing received?
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
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;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
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(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
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);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
As far as I know, OPP and PBAP features are provided for developers by Android API.
What they did was implement these profiles as applications, and ship it with the platform. You can see in your device that there are OPP and PBAP services running, so they will accept and handle the external connections, not your app.
The source code for these apps I mentioned are available here:
https://android.googlesource.com/platform/packages/apps/Bluetooth

Categories

Resources