簡體   English   中英

如何同時使用2個線程進行藍牙連接

[英]How can I use 2 threads at the same time for bluetooth connection

我在使用教程中的代碼時遇到了一些問題: https://developer.android.com/guide/topics/connectivity/bluetooth/transfer-data

我嘗試以這種方式連接:

_spinnerBT_Devices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
        _Selected_Device = (BluetoothDevice) _BT_Devices_list.get(i);
        _printf.setText(_Selected_Device.getName());
        _myThread = new ConnectThread(_Selected_Device);
        _myThread.run();
        _myService = new MyBluetoothService.ConnectedThread(_myThread.mmSocket);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        //_myThread.cancel();
    }
});

在我的串行藍牙上寫:

public void buttonUpClick() {
    _buttonUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            _printf.setText("Debug : UP");
            if(_myService.mmSocket.isConnected()){
                _myService.write("z".getBytes(StandardCharsets.UTF_8));
            }
        }
    });
}

但是,一旦我嘗試在上面寫字,應用程序就會崩潰,就像它不能同時使用兩個線程一樣。

編輯:我可以寫但只能寫一次而且它崩潰了

發現問題

這不是關於有 2 個線程,而是代碼崩潰的原因:

// Share the sent message with the UI activity.
                    Message writtenMsg = handler.obtainMessage(
                            MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
                    writtenMsg.sendToTarget();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM