我是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来打开它:
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);
后面跟着start off命令:
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模式,您将使用不同的套接字生成方法。你会使用不同的方法询问设备以获取支持的uid。有时你可能不得不求助于反射来激活隐藏的服务,例如Android的getuids () <版本15。这样的例子不胜枚举。>
对于初学者来说,使用工具来完成这项工作是有意义的。
我最喜欢的(我有偏见,我写的…)是BTWiz,它将封装上述内容流,还将为您提供异步IO的简单接口。