我正在尝试从蓝牙设备(Google Daydream Controller)获取所有数据,以响应Android应用程序中的某些用户输入。我找到了一个Web应用程序(https://github.com/mrdoob/daydream-controller.js),几乎可以根据需要读取数据。真的我只需要app按钮的按钮反馈。
但我无法连接!尝试连接时总是出错。其他人有类似的经历,但在不同的设置..我一直无法找到解决方案
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
答案 0 :(得分:1)
你需要从这样的后台线程中调用openDeviceConnection
:
Thread yourBGThread = new Thread( ){
@Override
public void run() {
try {
openDeviceConnection(mDevice);
} catch (IOException e) {
e.printStackTrace();
}
}
};
yourBGThread.start();
将此代码放在findBT()