Read Bluetooth Message in External android app - android

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

Related

NullPointerException pointed on int java.io.InputStream.read(byte[], int, int). How to approach a fix?

I've been following a BluetoothChat app tutorial similar to the sample provided by Google. Link to reference here GoogleSource . I can successfully connect to other phone's Bluetooth when I have not implemented the class that handles the input and output streams. But when I implemented the class (ConnectedThread), it crashes the app with the null pointer exception at the run() method on "bytes = inputSream.read(buffer)" inside that class. Any idea on how to approach a fix? Been plaguing me for days. Help would be appreciated. Thanks!
ConnectedThread class
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothsocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
bluetoothsocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = bluetoothsocket.getInputStream();
tmpOut = bluetoothsocket.getOutputStream();
} catch (IOException e) {
Log.e("ConnectedThrd->Cons", "Socket not created.");
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
//App crashes here(?)
bytes = inputStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e("ConnectedThrd->Run", "Connection Lost.", e);
e.printStackTrace();
connectionLost();
break;
}
}
}
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e("ConnectedThread->Write", "Empty write stream.");
}
}
public void cancel() {
try {
bluetoothsocket.close();
} catch (IOException e) {
Log.e("ConnectedThread->Cancel", "Failed to close socket.");
}
}
}
The problem was that the BluetoothSocket was null when I try to send a data to the other device causing this error. Adding a condition to check whether a connection is established helped me handle the error.

Bluetooth Chat App answering back same text I sent

Im using one app to send data to the elm327 through bluetooth and I'm trying the AT Z command but everything I get back from the OBD2 is AT Z too, my code is missing something or its supposed to answer like that ? I expected the AT Z to return elm327 text (tested with playstore apps and thats what I got)
// runs during a connection with a remote device
private class ReadWriteThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ReadWriteThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream
while (true) {
try {
// Read from the InputStream
bytes = inputStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
ChatController.this.start();
break;
}
}
}
// write to OutputStream
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Perhaps you're not reading enough – make sure you concatenate all fragments you read until you receive the actual prompt \r>.
ELM327 usually starts out in echo mode, where it echos every command you are giving to it, that may explain why you're reading it back. Use ATE0 to turn off this behavior.
In general, https://www.sparkfun.com/datasheets/Widgets/ELM327_AT_Commands.pdf explains all that.

Xamarin Bluetooth InputStream not reading all the bytes (sometime)

I used this code to read the reply of a Bluetooth not LE device.
The solution is a Xamarin Forms project and the code is in the DependencyService.
using Android.Bluetooth;
....
public byte[] GetCommand()
{
byte[] rbuffer = new byte[200];
try
{
// Read data from the device
while (!_socket.InputStream.CanRead || !_socket.InputStream.IsDataAvailable())
{
}
int readByte = _socket.InputStream.Read(rbuffer, 0, rbuffer.Length);
}
catch (Java.IO.IOException e)
{
}
return rbuffer;
}
How is it possible to solve it?
I would use the following code instead:
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
This is working for me to get bluetooth information from an Arduino! :)

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

Bluetooth getInputStream gets multiple/splitted Datapackages?

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.

Categories

Resources