我前段时间创建了 I 类来帮助解决这种情况,你可以在这里看到。它允许您发送数据并异步等待它。例如,您将以这种方式使用它:
BluetoothHelper mBluetoothHelper = new BluetoothHelper(this, "bluetoothDeviceName", false, null);
mBluetoothHelper.setConnectionDialog(true); // Shows a dialog while connecting
mBluetoothHelper.connect(true); // Connect to Bluetooth device
因此,以这种方式连接到蓝牙设备,现在要接收您需要实现的数据OnNewBluetoothDataReceivedListener
:
mBluetoothHelper.setOnNewBluetoothDataReceived(this);
// Called when you receive data from Bluetooth
@Override
public boolean onNewBluetoothDataReceivedListener(InputStream mBTIn, OutputStream mBTOut) {
}
所以你不需要等待任何东西,当你接收到数据时它会被异步调用。发送数据:
mBluetoothHelper.write(data);
您将必须实现String
使用此方法编写的方法。所以你需要
- OnNewBluetoothDataReceivedListener.java
- 蓝牙助手.java
- 您还需要在布局中
DeviceList.java
使用device_list.xml和在strings.xml
<string name="scanning"> Scanning…</string>
<string name="select_device"> Select device</string>
<string name="none_paired"> No paired devices</string>
<string name="none_found"> No devices were found</string>
<string name="title_paired_devices"> Paired devices</string>
<string name="title_other_devices"> Other available devices</string>
<string name="button_scan"> Scan</string>
并在AndroidManifest.xml
:
<activity android:name=".DeviceListActivity"
android:label="@string/select_device"
android:theme="@android:style/Theme.Holo.Dialog"
android:configChanges="orientation|keyboardHidden" >
</activity>
您需要这个,因为当您扫描以连接到蓝牙设备时,它会向您显示可用设备的列表,BluetoothHelper.java
如果您不想要它,您可以对其进行修改。