Evening fellow programmers,
am relatively new to android studio, and it's my first time dealing with bluetooth, receivers, broadcasts and such stuff.. I followed some tutorials and created my monitoring app, the app is supposed to read data sent by HC-06 module from arduino, yet I had a pump with the connect thread, it keeps catching the socket.close() instead of trying the socket.connect() and I have no idea why is that happening..
here is the code for my ConnectThread.run():
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket
using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket
" + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection
in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " +
MY_UUID_INSECURE );
}
connected(mmSocket,mmDevice);
}
And the thrown exception:
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#3390c6f, mSocketState: INIT
D/BluetoothConnectionServ: run: Closed Socket.
run: ConnectThread: Could not connect to UUID: 00001101-0000-1000-8000-00805f9b34fb
connected: Starting.
However, connectedThread continues to work even when the socket is closed, idk if that's how it works, but here is the ConnectedThread.run():
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) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("theMessage",incomingMessage);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
And its exceptions:
D/BluetoothConnectionServ: ConnectedThread: Starting.
E/BluetoothConnectionServ: write: Error reading Input Stream. socket closed
Related
So I have set up a serial connection between a paired raspberry pi device running a pybluez rfcomm-server. I have paired my Android device to the Pi, and then put together a Bluetooth service that leverages a Thread to handle the two-way asynchronous comms. Most of the code is straight from the Android Developers Guides on Bluetooth Socket communication here and reading/writing to the socket as discussed here
The issue arises when I manually disconnect from the Pi by closing down my socket and closing down the thread handling the communication. I can reconnect, spin up another thread, and successfully start communicating with the Pi again but this is where it gets weird, IOExcpetions start getting thrown and Logcat is pissing and moaning that and "Error occured sending data". The exception is caught obviously and like I said earlier, the Pi is still happily receiving the messages. I can repeat this by disconnecting and reconnecting again and again.
Normally I would just shrug and move on because it works right? But I don't feel like any IOExceptions should be being thrown.
Here is some code:
(BtBus is an RxJava based message bus I made, all messages are send on background threads and received on the main thread)
BluetoothService - connect() and disconnect() methods
public void connect(){
if(btAdapter == null) {
Log.e(TAG, "No bluetooth adapter available");
}
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
if(device.getName().contains("raspberry")){
pi = device;
Log.d(TAG, "using paired device: " + pi.getName());
break;
}
}
}else {
Log.d(TAG, "No BT devices paired");
}
if(pi != null) {
if(btAdapter.isDiscovering())
btAdapter.cancelDiscovery();
Observable.fromCallable(this::connectSocket)
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.subscribe(socket -> {
if(socket != null){
try {
socket.connect();
Log.d(TAG, "Socked with device created, creating thread");
connectedThread = new ConnectedThread(socket);
Log.d(TAG, "Thread created, starting...");
connectedThread.start();
Log.d(TAG, "Thread Started");
isConnected = true;
BtBus.publish(new BtAction("CONNECTION_ESTABLISHED"));
}catch (IOException e) {
Log.d(TAG, "Unable to connect socket");
e.printStackTrace();
}
}
});
}
//disconnect
public void disconnect() {
if(socket != null) {
connectedThread.cancel();
}
}
private BluetoothSocket connectSocket(){
try {
socket = pi.createInsecureRfcommSocketToServiceRecord(DEFAULT_UUID);
return socket;
}catch (IOException e){
Log.d(TAG, "Failed to get service with Pi UUID");
return null;
}
}
ConnectedThread
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
private 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();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
BtBus.subscribe(action -> {
if(action instanceof BtAction){
write(((BtAction) action).getAction().getBytes());
}
});
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
BtAction action = BtCommFilter.getActionType(mmBuffer);
BtBus.publish(action);
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
Here is the stack relevant stack trace from the exception
E/BluetoothService: Error occurred when sending data
java.io.IOException: socket closed
at android.net.LocalSocketImpl$SocketOutputStream.write(LocalSocketImpl.java:130)
at android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:659)
at android.bluetooth.BluetoothOutputStream.write(BluetoothOutputStream.java:85)
at java.io.OutputStream.write(OutputStream.java:82)
at com.medspark.tenscontroller.service.BluetoothService$ConnectedThread.write(BluetoothService.java:183)
at com.medspark.tenscontroller.service.BluetoothService$ConnectedThread.lambda$new$0$BluetoothService$ConnectedThread(BluetoothService.java:157)
at com.medspark.tenscontroller.service.BluetoothService$ConnectedThread$$Lambda$0.accept(Unknown Source)
at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:60)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:200)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
As you can see, when I close the connection the socket is properly closed and the thread is disposed of. When I reconnect a new socket is created and a new thread spun up, so I don't understand where the IOException is being thrown. Thanks in advance.
My application worked fine under Android 2.3.3 to 4.1.2, but since Android 4.2.2 and Android 4.3, I have a
fatal signal 11 (SIGSEGV) at 0x00....
when I close the bluetooth socket.
I've searching trough a lot of forums, and the main response is that the
BluetoothSocket.close();
is called from two different thread at the same time, but it's not the case in my code.
I'm using Samsung Galaxy Note 2 under A4.1.2 (works ok) and Nexus 4 for A4.2.2 and 4.3.
Thank you in advance for your suggestions !
EDIT 1 : here are the 2 threads that manipulate the Bluetooth socket.
the first :
/**
* This thread runs while attempting to make an outgoing connection with a
* device. It runs straight through; the connection either succeeds or
* fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
//private final UUID MY_UUID = java.util.UUID.randomUUID();
public ConnectThread(BluetoothDevice device) {
if(D) Log.d(TAG, "/S4B/ start connectThread ");
mmDevice = device;
BluetoothSocket connection = null;
// Get a BluetoothSocket for a connection with the given BluetoothDevice
try {
if(D) Log.i(TAG,"/S4B/ Create RF Socket");
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
connection = (BluetoothSocket) m.invoke(device, 1);
//connection = device.createRfcommSocketToServiceRecord(MY_UUID);
Utils.pause(100);
} catch (Exception e) {
Log.e(TAG, "/S4B/ create() failed", e);
}
mmSocket = connection;
if(D) Log.i(TAG,"/S4B/ Socket initialized");
}
public void run() {
if(D) Log.i(TAG, "/S4B/ BEGIN mConnectThread");
setName("ConnectThread");
if (mmSocket != null) {
// Always cancel discovery because it will slow down a connection
if(mAdapter.isDiscovering()){
mAdapter.cancelDiscovery();
}
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a successful connection or an exception
if(D) Log.i(TAG,"/S4B/ Start socket connection");
mmSocket.connect();
if(D) Log.i(TAG,"/S4B/ End of socket connection");
} catch (Exception e) {
Log.e(TAG, "/S4B/ socket connect failed", e);
// Close the socket
try {
mmSocket.close();
if(D) Log.i(TAG,"/S4B/ close socket");
} catch (IOException e2) {
Log.e(TAG,"/S4B/ unable to close() socket during connection failure",e2);
}
//Turn off the bluetooth - the Bluetooth STATE_OFF Broadcast will be received in welcome.class
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothConnectionService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
} else {
BluetoothConnectionService.this.start();
connectionFailed();
}
}
public void cancel() {
try {
if (mmSocket != null) {
mmSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "/S4B/ close() of connect socket failed", e);
}
}
}
and the second :
/**
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final DataInputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "/S4B/ Create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
if(D) Log.i(TAG,"/S4B/ Get input and output stream");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
isConnected = true;
} catch (IOException e) {
Log.e(TAG, "/S4B/ Temp sockets not created", e);
isConnected = false;
}
mmInStream = new DataInputStream(tmpIn);
mmOutStream = tmpOut;
}
public void run() {
setName("ConnectedThread");
Log.i(TAG, "/S4B/ BEGIN mConnectedThread");
while (isConnected) {
Utils.pause(50);
isConnected = checkConnection();
}
}
/**
* Check if the connection is still alive
*
* #return true or false
*/
private boolean checkConnection() {
synchronized (mmInStream) {
try {
int len = mmInStream.available();
if (len > 0) {// Checks the available amount
byte b[] = new byte[len];
if(D) Log.i(TAG,"/S4B/ start mmInStream readFully");
mmInStream.readFully(b, 0, len);
mHandler.obtainMessage(MESSAGE_READ, len, -1, b).sendToTarget();
}
return true;
} catch (IOException ioe) {
Log.e(TAG, "/S4B/ check connection, disconnected", ioe);
connectionLost();
return false; // Connection is lost.
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer
* The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "/S4B/ Exception during write", e);
connectionLost();
return;
}
// Share the sent message back to the UI Activity
mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
Utils.pause(1000);
} catch (IOException e) {
Log.e(TAG, "/S4B/ close() of connect socket failed", e);
}
}
}
EDIT 2 : I tried to use only one thread to be sure that there is no access in parrallel to
BluetoothSocket
but the result is exactly the same. As soon as I call
BluetoothSocket.close();
I get the fatal signal 11 and the app crashes.
I ran into this problem as well. However, for me close() was not the cause. The problem was accessing the socket after close(). Specifically, the call to available() on the socket's inputstream after the socket was closed caused the segfault.
I had the exact same problem. It helped to me before closing socket call
mConnectedThread.interrupt()
from outer class, and to ConnectedThread run() method add
public void run() {
...
while (condition) {
if (isInterrupted())
return;
...
}
...
}
to make sure thread doesn't read anything from socket's stream. After that you could call mmSocket.close()
I faced same problem with Android 4.4.2 in Galaxy Grand 2 device
I fixed the problem with help of answer given by #markrileybot answer
I was accessing the socket.available() method after close() call is done by my code.
To add more to #markrileybot answer :
I had also added condition before calling socket.close() :
public void cancel() {
try {
if(mmSocket.isConnected()) // this is condition
mmSocket.close();
Utils.pause(1000);
} catch (IOException e) {
Log.e(TAG, "/S4B/ close() of connect socket failed", e);
}
}
1 If you are sharing same socket between multiple threads, then this condition should be added which will prevent calling close() if socket is already closed (not connected)
2 Before calling socket.available() or socket.write(), we should check socket.isConnected() and if it returns true then only we should process further
I am trying with blue-tooth chat example for api-10, in my micromax pfhone.
When I scanning for devices it showing the list for both secure and non secure.
But When I try to connect it showing unable to connect.
And UUIDs are:
private static final UUID MY_UUID_SECURE = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
I tried this post,
Service discovery failed exception using Bluetooth on Android , but no change.
Any ideas?
This is my code for connecting to a blue-tooth device while pairing. I got this code from android api-10 samples:
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
connectionFailed();
return;
}
An obvious question, but still:
Did you register the 2 Bluetooth permissions in the Android manifest file?
I have get below UUID from
"Service discovery failed" from Android Bluetooth Insecure Rfcomm
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Using this UUID I am able to connect other handsets(Bada,Blackberry) except android.
below is code that i have get from android sample
/
**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
BluetoothSocket tmp = null;
public ConnectThread(BluetoothDevice device)
{
mmDevice = device;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try
{
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.d(TAG, "tmp = "+tmp.toString());
}
catch (IOException e)
{
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run()
{
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try
{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, " before connecting mmsocket.connect()");
mmSocket.connect();
Log.d(TAG, " after connecting mmsocket.connect()");
}
catch (IOException e)
{
Log.d(TAG, " before connectionFailed()");
connectionFailed();
Log.d(TAG, " after connectionFailed()");
Log.d(TAG, "after connectiofailed exception is: "+ e.toString());
// Close the socket
try
{
mmSocket.close();
}
catch (IOException e2)
{
Log.d(TAG, "unable to close() socket during connection failure: "+ e2.toString());
}
// // Start the service over to restart listening mode
// BluetoothChatService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothService.this)
{
mConnectThread = null;
}
Log.d(TAG, " before connected mmsocket and mmdevice");
// Start the connected thread
connected(mmSocket, mmDevice);
Log.d(TAG, "after connected mmsocket and mmdevice");
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
I am getting error service discovery failed.
I want to pair 2 android handsets
Please help !!!
I would like to develop an application for sending a message to multiple devices through blue tooth.I know blue tooth is a point to point communication even though i would like to connect and send a message as following steps:
1.Get the list of paired devices
2.Select a device from paired list
3.Connect to paired device , send a message to selected paired device
4.Disconnect from device
5.Get connection to another device and so on (one after another).
I am getting paired devices addresses list as follows:
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedList.add(device.getAddress());
}
Log.v("11111111", "11111111111"+dev);
}
I am trying to connect to them and sending a message when user clicks on a button as follows:
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = "Haiii";
for(int i=0;i<dev.size();i++){
Log.v("device", "111111 : "+pairedList.get(i));
mbService.connect(mBtAdapter.getRemoteDevice(pairedList.get(i)));
mbService.write(message.getBytes());
mbService.stop();
}
}
});
From the above code i am getting connection when loop pairedList.get(0).But the message is not sending to another device.In another device api sample application has installed.
If I use pairedList.get(i) it is not connecting to any devices even single device also.
please help me .
try to create separate threads for each connection - I had a similar issue and creating a new thread for each connection solved it nicely. By the way I even create a new thread to establish the connection - so establishing the connection does not block the UI. Got this from the BT sample code...
to create a new thread to establish a connection:
mConnectBluetoothThread = new ConnectBluetoothThread(device);
mConnectBluetoothThread.start();
where ConnectBluetoothThread is defined like:
public ConnectBluetoothThread(BluetoothDevice device) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
// TODO
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(this.getClass().getSimpleName(),
"unable to close() socket during connection failure",
e2);
}
return;
}
// Reset the ConnectThread because we're done
synchronized (InterBT.this) {
mConnectBluetoothThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(),
"close() of connect socket failed", e);
}
}
}
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device) {
if (DEBUG)
Log.d(this.getClass().getSimpleName(), "connected");
// Cancel the thread that completed the connection
if (mConnectBluetoothThread != null) {
mConnectBluetoothThread.cancel();
mConnectBluetoothThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedBluetoothThread != null) {
mConnectedBluetoothThread.cancel();
mConnectedBluetoothThread = null;
}
// Cancel the accept thread because we only want to connect to one
// device
// if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread =
// null;}
// Start the thread to manage the connection and perform transmissions
mConnectedBluetoothThread = new ConnectionThreadBT(socket);
mConnectedBluetoothThread.start();
setState(STATE_CONNECTED);
}
and also create a new class ConnectionThreadBT that handles the connection to read and write:
public class ConnectionThreadBT extends ConnectionThreadBase {
private static final boolean DEBUG = true;
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
byte[] responseBuffer = new byte[4096 * 4];
int responseBufferLen = 0;
public ConnectionThreadBT(BluetoothSocket socket) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
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(this.getClass().getSimpleName(), "temp sockets not created",
e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
//we have successfully connected to BT
//now inform UI
Home_Screen.sendMessageToHomeScreen(
Home_Screen.MESSAGE_INTERBT_CONNECTION_TESTED,
Home_Screen.CONNECTION_SUCCESS, true);
}
and then to write just call this method which is also defined within ConnectionThreadBT
public void sendMsg(MyBuffer buffer){
try {
mmOutStream.write(buffer);
mmOutStream.flush();
successfullyWritten = true;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(),
"Exception during write", e);
successfullyWritten = false;
}
to read either do the same or start a monitoring loop in the run method which keeps reading as long as the connectedThread is alive and reports back any read information through a handler similar to the UI screen update