BluetoothEventLoop( 2255): Device property changed.Bluetooth Connection Lost - java

I have a sample application which transfers 30 char length data through Bluetooth.Data transfer was proper for four days,and then disconnected.Then after,when ever connection is established after few minutes Bluetooth connection is lost.adding adb logs and code.
Why i am getting disconnect from platform due to device property change ? when will the device property change ? is the device property change is the reason to loose Bluetooth connection?
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
Log.i("12345", "Socket set");
}
public void run() {
Log.i("12345", "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();
Log.i(TAG, "Closing Socket 3");
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2);
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
Logs :
09-12 11:16:36.230 V/BluetoothEventLoop.cpp( 2255): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/3179/hci0/dev_22_89_8E_A9_50_1C
09-12 11:16:36.230 D/BluetoothEventLoop( 2255): Device property changed
09-12 11:16:36.240 D/BluetoothA2DPStateReceiver(20246): BluetoothA2DPStateReceiver constructor call()
09-12 11:16:36.245 D/BluetoothA2DPStateReceiver(20246): onReceive(): action = android.bluetooth.device.action.ACL_DISCONNECTED
09-12 11:16:36.245 D/BluetoothA2DPStateReceiver(20246): ACTION_ACL_DISCONNECTED
09-12 11:16:36.245 D/BluetoothA2DPSinkInfo(20246): checkBlackListCarkit() : isBlackListCarkit false
09-12 11:16:36.660 D/KeyguardViewMediator( 2255): setHidden false

May be due to the link loss, BT adapter had initiated the property changed command to report link disconnected to the upper layers. Please check in multitple devices.

Related

what is the purpose of this tmp variable in android sample bluetooth chat application

I'm just analyzing one of android sample applications - the bluetooth chat: https://developer.android.com/samples/BluetoothChat/project.html . I'm looking at the BluetoothChatService class ( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html ), at the constructor of its inner class called ConnectThread. There is such piece of code there:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
BluetoothSocket tmp = null;
(...)
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;
}
(...)
I don't understand - why they first assign the object to the tmp value and then copy it to mmSocket attribute? They could do it a bit simpler, this way:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
(...)
public ConnectThread(BluetoothDevice device, boolean secure) {
(...)
try {
if (secure) {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
}
Shortly, because mmSocket is marked as final variable.
Let's see that your version of code. If method createRfcommSocketToServiceRecord or method createInsecureRfcommSocketToServiceRecord throws exception, the variable is not initialized. So the temporary variable makes sure that there is atleast null to be assigned to mmSocket.
That's the reason.

Android app connecting to java application server through bluetooth only after pairing

Good day every one! So I have this android app which acts as a client and tries to connect to a java application on my PC that has a Bluetooth server component in it.
The issue I'm facing is that the connection only establishes when I don't have my PC in the paired devices list of my Nexus 5. In other words they only connect when they are paired. Therefore I've been forced to remove My PC from the list of Paired devices every time that I want to have a connection or else the connection fails.
I have used this Simple Android and Java Bluetooth Application for the base of the server side application:
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
public class WaitThread implements Runnable{
public WaitThread() { }
#Override
public void run() {
waitForConnection();
}
/** Waiting for connection from devices */
private void waitForConnection() {
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
UUID uuid = new UUID("04c6032b00004000800000805f9b34fc", false);
System.out.println(uuid.toString());
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out.println("Bluetooth is not turned on.");
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
// waiting for connection
while(true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
and used the BluetoothChat from android sample projects for base of the client side:
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
Handler mHandler;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final UUID MY_UUID = UUID
.fromString("04c6032b-0000-4000-8000-00805f9b34fc");
public ConnectThread(BluetoothDevice device, Handler handler) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmpSocket = null;
mmDevice = device;
mHandler = handler;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
tmpSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Message msgException = new Message();
msgException.setTarget(mHandler);
msgException.what = Constants.DISCONNECTED_HANDLER;
msgException.sendToTarget();
}
mmSocket = tmpSocket;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
Message msg1 = new Message(); // handler. we use it to know when de
// device has been connected or
// disconnected in the UI activity
msg1.setTarget(mHandler);
msg1.what = Constants.CONNECTING_HANDLER;
msg1.sendToTarget();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
// handler
Message msg2 = new Message();
msg2.setTarget(mHandler);
msg2.what = Constants.CONNECTED_HANDLER;
msg2.setTarget(mHandler);
msg2.sendToTarget();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
System.out.println("alex - NO connected");
Message msgException = new Message();
msgException.setTarget(mHandler);
msgException.what = Constants.DISCONNECTED_HANDLER;
msgException.sendToTarget();
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
public BluetoothSocket getBTSocket() {
return mmSocket;
}
}
I have a feeling this might be because of the UUID that I'm using. The UUIDs that worked for me were the followings:
04c6032b00004000800000805f9b34fc
0000110500001000800000805f9b34fb
I am using the similar UUIDs in both applications. Any Idea what might be causing this issue?
Strangely enough, today when I used a Bluetooth dongle instead of my own laptop's Bluetooth the problem got resolved. Therefore It was not an issue on behalf of the software component.

Using Extended Class

I'm new to java / object oriented language and wanted to get some help on the syntax.
I have a class defined in ConnectThread.java as
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
From here I tried to create a thread and connect this thread by writing this code in my connect method:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice targetdevice;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
// Loop through paired devices
for (BluetoothDevice device : pairedDevices)
{
if (device.getName().equals("HC-06"))
targetdevice = device;
}
}
Thread writeThread = new Thread();
writeThread.ConnectThread(targetdevice);
I get the error in the last line and it says "The method ConnectThread(BluetoothDevice) is undefined for the type Thread"
I thought since ConnectThread is an extended class of Thread, I could use the methods under it. Is this not the case? What would be the right way to go about doing this?
Thanks!
Change your last two strings to:
Thread writeThread = new ConnectThread(targetdevice);
When you need to start your ConnectThread use start() method:
writeThread.start(); //If you need start run() method of ConnectThread.

Communication Bluetooth android-arduino

I have modified the android app "Bluetooth Chat" that you can find in android sdk examples version 2.1
The app estabilished a bluetooth connection with arduino, and, when with the app I send 0 or 1, arduino send a simple message "You have pressed 0 or 1".
It works if I test with eclipse's debug, but when I test with my smartphone, the result in the display is different, arduino's string is fragmented
example: smartphone: 0 -> arduino "You have pressed 0 or 1"
smartphone display: "y"
"ou pr"
The rest of the string was lost or not shown in the display.
Can you help me?
No error in logcat, only this bug.
This is the code:
public class BluetoothLampService {
// Debugging
private static final String TAG = "BluetoothLampService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME = "BluetoothLamp";
// Unique UUID for this application - Standard SerialPortService ID
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter Adapter;
private final Handler Handler;
// private AcceptThread AcceptThread;
private ConnectThread ConnectThread;
private ConnectedThread ConnectedThread;
private int State;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
/**
* Constructor. Prepares a new BluetoothChat session.
* #param context The UI Activity Context
* #param handler A Handler to messages back to the UI Activity
*/
public BluetoothLampService(Context context, Handler handler) {
Adapter = BluetoothAdapter.getDefaultAdapter();
State = STATE_NONE;
Handler = handler;
}
/**
* Set the current state of the chat connection
* #param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
State = state;
// Give the new state to the Handler so the UI Activity can update
Handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
* Return the current connection state. */
public synchronized int getState() {
return State;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
// Cancel any thread attempting to make a connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to listen on a BluetoothServerSocket
// if (AcceptThread == null) {
// AcceptThread = new AcceptThread();
// AcceptThread.start();
// }
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* #param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
// Cancel any thread attempting to make a connection
if (State == STATE_CONNECTING) {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to connect with the given device
ConnectThread = new ConnectThread(device);
ConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Cancel the thread that completed the connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
// Start the thread to manage the connection and perform transmissions
ConnectedThread = new ConnectedThread(socket);
ConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
Handler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (State != STATE_CONNECTED) return;
r = ConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
/*
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket ServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = Adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
ServerSocket = tmp;
}
public void run() {
//Looper.prepare();
setName("AcceptThread");
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (State != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = ServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothLampService.this) {
switch (State) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
// Looper.loop();
}
public void cancel() {
try {
ServerSocket.close();
} catch (IOException e) {
}
}
}
*/
/**
* 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 Socket;
private final BluetoothDevice Device;
public ConnectThread(BluetoothDevice device) {
Device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
Socket = tmp;
}
public void run() {
Looper.prepare();
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
Adapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
Socket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
Socket.close();
} catch (IOException e2) {}
// Start the service over to restart listening mode
BluetoothLampService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothLampService.this) {
ConnectThread = null;
}
// Start the connected thread
connected(Socket, Device);
Looper.loop();
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
/**
* 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 Socket;
private final InputStream InStream;
private final OutputStream OutStream;
public ConnectedThread(BluetoothSocket socket) {
Socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
InStream = tmpIn;
OutStream = tmpOut;
}
public void run() {
Looper.prepare();
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
// FUNZIONANTE
bytes = InStream.read(buffer);
Log.i("BYTES", Integer.toString(bytes));
//String dati = new String(buffer);
//fine aggiunto da me
// Send the obtained bytes to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_READ, 27, -1, buffer).sendToTarget();//buffer
} catch (IOException e) {
connectionLost();
break;
}
}
Looper.loop();
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
OutStream.write(buffer);
// Share the sent message back to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
}
Have you already gived permission to your android app on your Manifest file?
uses-permission android:name="android.permission.BLUETOOTH" /
uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /
Then check the serial baude rate on your arduino serial connection too.
Kindly try by first pairing the device explicitly from your Android phone's settings. Usually the pair code is 1234

Android - BluetoothChat example - Why have they used synchronized in this case?

Ok, so I am little perplexed as to why synchronized was used in the line marked below.
To me, you only use synchronized where a block of code will potentially be accessed by multiple threads however this code is only ever called from this thread in its run method.
An instance of mConnectThread is declared as a field at the very start of the class.
public class BluetoothChatService {
// Member fields
private ConnectThread mConnectThread;
Any ideas?
/**
* 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 String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
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;
}
/********* THIS BIT OF CODE BELOW IS WHAT I AM ASKING ABOUT **********/
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
/**********************************^^*********************************/
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
Cheers
You can have multiple ConnectThread objects going simultaneously, which means multiple threads in the same run method(technically, copies of the run method, but the same code), though they'll all have access to different member variables. The synchronized block is syncing on an external object, so I suspect there's a synchronized block somewhere else in the program that looks like
synchronized (BluetoothChatService.this)
{
if (mConnectThread != null)
do some work that would throw NPE without the check.
}
Edit:
To clarify, they aren't preventing two threads from accessing the same block of code, they're preventing two threads from accessing the same variable from different sections of code.

Categories

Resources