我正在尝试从蓝牙设备(Google Daydream Controller )获取所有数据,以对 Android 应用程序中的某些用户输入使用react。我找到了一个 Web 应用程序 ( https://github.com/mrdoob/daydream-controller.js ),它几乎可以读取我需要的数据。真的,我只需要应用程序按钮的按钮反馈。
但是我无法连接!尝试连接时总是出错。其他人也有类似的经历,但设置不同。我一直找不到解决方案
public class TryAgain extends AppCompatActivity {
private static final String UUID_SERIAL_PORT_PROFILE = "00001101-0000-1000-8000-00805F9B34FB";
private static final String TAG = "tag";
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mDevice;
private BluetoothSocket mSocket = null;
private BufferedReader mBufferedReader = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_try_again);
findBT();
try {
openDeviceConnection(mDevice);
} catch (IOException e) {
e.printStackTrace();
}
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
System.out.println("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("Daydream controller"))
{
mDevice = device;
break;
}
}
}
System.out.println("Bluetooth Device Found");
}
private void openDeviceConnection(BluetoothDevice device)
throws IOException {
InputStream aStream = null;
InputStreamReader aReader = null;
try {
mSocket = device.createRfcommSocketToServiceRecord( getSerialPortUUID() );
mSocket.connect();
aStream = mSocket.getInputStream();
aReader = new InputStreamReader( aStream );
mBufferedReader = new BufferedReader( aReader );
} catch ( IOException e ) {
Log.e( TAG, "Could not connect to device", e );
close( mBufferedReader );
close( aReader );
close( aStream );
close( mSocket );
throw e;
}
}
private void close(Closeable aConnectedObject) {
if ( aConnectedObject == null ) return;
try {
aConnectedObject.close();
} catch ( IOException e ) {
}
aConnectedObject = null;
}
private UUID getSerialPortUUID() {
return UUID.fromString( UUID_SERIAL_PORT_PROFILE );
}
}
第一步是读取设备发送的数据流,然后提取信息以获取答题器信息。当然,连接到设备是必不可少的,这就是我现在正在努力的地方。
错误信息:
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
最佳答案
您需要像这样从后台线程调用openDeviceConnection
:
Thread yourBGThread = new Thread( ){
@Override
public void run() {
try {
openDeviceConnection(mDevice);
} catch (IOException e) {
e.printStackTrace();
}
}
};
yourBGThread.start();
将此代码放在 findBT()
下方
关于android - 蓝牙 socket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699163/