[英]Android: Bluetooth listening thread is blocking UI thread
my ListeningThread is freezing the UI thread of the Barometer activity although it shouldn't. 我的ListeningThread冻结了Barometer活动的UI线程,尽管不应该这样做。 I have no idea why this is happening.
我不知道为什么会这样。 Help needed :)
需要帮助 :)
This is my ListeningThread: 这是我的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.
我试图在此方法周围加上注释,然后一切正常。
You should put the while(true)
code inside the method public void run()
. 您应该将
while(true)
代码放入方法public void run()
。 Not in the public void start()
as documented here https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html 如https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html所述,不在
public void start()
中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.