Android:蓝牙监听线程阻止UI线程

时间:2016-06-03 20:34:53

标签: java android multithreading bluetooth android-bluetooth

我的ListeningThread正在冻结Barometer活动的UI线程,尽管它不应该。我不知道为什么会这样。需要帮助:)

这是我的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();
    }
}
}

这是使用线程和冻结的活动:

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();
}

}

我确信问题出现在线程的run-method中。我尝试用注释包围这个方法,然后一切运行正常。

1 个答案:

答案 0 :(得分:2)

您应该将while(true)代码放在方法public void run()中。不在此处记录的public void start() https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html