【发布时间】:2014-06-28 05:24:16
【问题描述】:
我是 Android 平台的新手。我正在使用需要集成蓝牙的应用程序。要求不是手动连接和断开蓝牙耳机(HSP配置文件),而是应该可以在应用程序内连接和断开连接。是否可以在运行OS 4.2、4.3和4.4的Android设备中连接和断开设备。如果有的话有这个问题的解决方案,请给我同样的建议。
【问题讨论】:
我是 Android 平台的新手。我正在使用需要集成蓝牙的应用程序。要求不是手动连接和断开蓝牙耳机(HSP配置文件),而是应该可以在应用程序内连接和断开连接。是否可以在运行OS 4.2、4.3和4.4的Android设备中连接和断开设备。如果有的话有这个问题的解决方案,请给我同样的建议。
【问题讨论】:
有可能,但有时没那么简单。
要连接,首先检查您正在运行的设备是否完全支持 BT:
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter==null) {
// device not support BT
}
如果没有 - 优雅地禁用应用的 BT 部分并继续。
如果支持,检查当前是否启用(记住,用户可以 与其他通信渠道一样打开和关闭 BT):
boolean isEnabled = bluetoothAdapter.isEnabled(); // Equivalent to: getBluetoothState() == STATE_ON
如果未启用,则允许用户通过触发 ACTION_REQUEST_ENABLE 意图来打开它:
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, ENABLE_BT_CODE);
一旦您明确了可用性,就可以查找您想要的特定设备。 从 Android 维护的绑定设备列表开始总是一个好主意:
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device: pairedDevices) {
if (device is the one we look for) {
return device;
}
}
如果没有,您将需要发出 BT 发现命令。
绝不能在 UI 线程上执行发现,因此请生成一个线程(使用 AsyncTask、Executer 等来完成工作)。
当 BT 连接操作仍在进行时,不应执行发现。这 对设备资源的影响太大。
首先设置您的发现接收器:
discoveryReceiver = new BroadcastReceiver() {
private boolean wasFound = false;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println(action);
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
discoveryStatus = STARTED;
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveryStatus = FINISHED;
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device is what we look for) {
stopDiscovery(context);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(discoveryReceiver, filter);
然后跟随一个启动命令:
boolean started = bluetoothAdapter.startDiscovery(); //async call!
if (!started) {
// log error
}
找到您的设备后,您需要创建一个专用的 BT 插座:
BluetoothSocket clientSocket = null;
try {
if (secureMode == SECURE) {
clientSocket = device.createRfcommSocketToServiceRecord(serviceUuid);
}
else { // INSECURE
clientSocket = device.createInsecureRfcommSocketToServiceRecord(serviceUuid);
}
if (clientSocket == null) {
throw new IOException();
}
} catch (IOException e) {
// log error
}
接着是连接命令:
clientSocket.connect(context);
一旦连接返回,您可以像使用套接字的方式和完成后一样来回传输数据:
clientSocket.close(context);
以上描述了一般流程。在许多情况下,您的工作会更加困难:
对于安全和不安全的 BT 模式,您将使用不同的套接字生成方法。你将使用不同的 向设备询问支持的 UUID 的方法。您有时还可能不得不诉诸反射来激活隐藏服务,例如getUuids() for Android
使用工具来完成这项工作是有意义的,尤其是对于初学者而言。
我最喜欢的(我有偏见,我写的..)是BTWiz,它将封装上述内容 从您那里流出,还将为您提供一个简单的异步 IO 接口。随意尝试一下。
【讨论】: