Reputation: 1
my ListeningThread is freezing the UI thread of the Barometer activity although it shouldn't. I have no idea why this is happening. Help needed :)
This is my ListeningThread:
public class ListeningThread extends Thread {
String TAG = "bluetoothThread";
private final BluetoothServerSocket bluetoothServerSocket;
BluetoothAdapter bl;
public ListeningThread(BluetoothAdapter bluetoothAdapter, String appName) {
BluetoothServerSocket temp = null;
bl = bluetoothAdapter;
try {
temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(appName, Constants.MY_UUID_SECURE);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void start() {
Log.d(TAG, "ListeningThread running");
BluetoothSocket bluetoothSocket;
//This will block while listening until a BluetoothSocket is returned or an exception occurs
while (true) {
try {
bluetoothSocket = bluetoothServerSocket.accept();
Log.d(TAG, "ListeningThread connected");
} catch (IOException e) {
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
// Manage the connection in a separate thread
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the activity using the thread and freezing:
public class BarometerActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barometer);
if (SingletonBluetoothAdapter.bluetoothAdapter == null) {
SingletonBluetoothAdapter.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
bluetoothAdapter = SingletonBluetoothAdapter.bluetoothAdapter;
ListeningThread t = new ListeningThread(bluetoothAdapter, getString(R.string.app_name));
t.start();
}
}
I am sure the problem is somewhere in the run-method of the thread. I tried to surround this method with a comment and then everything runs fine.
Upvotes: 0
Views: 357
Reputation: 3664
You should put the while(true)
code inside the method public void run()
. Not in the public void start()
as documented here https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Upvotes: 2