我正在开发显示某些连接的蓝牙低功耗设备列表的应用程序,因此用户可以选择要配置哪一个。
问题是你不能只列出所有连接的设备。据我所知,有三种可能的方法:
> < li>
使用蓝牙配置文件
bluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
这会失败,因为当设备连接时,android不会连接到GATT服务器,所以设备既不GATT_SERVER也不GATT配置文件。
bluetoothDevice.connectGatt(getApplicationContext(), false, gattCallback);
设备可以在GATT_SERVER和GATT profile下找到。低能耗设备不支持其他配置文件。
列出配对的设备并尝试在每个设备上连接Gatt
List<BluetoothDevice> connectedDevices = new ArrayList<BluetoothDevice>();
for(BluetoothDevice device : bluetoothAdapter.getBondedDevices()) {
BluetoothGatt gatt = device.connectGatt(getApplicationContext(), false, gattCallback);
if(gatt != null) {
connectedDevices.add(device);
}
gatt.disconnect();
}
无法使用此方法,因为它无法确定设备是否已连接或仅在范围内但未连接
在系统引导时,启动服务侦听ACL_CONNECTED和ACL_DISCONNECTED意图,并维护已连接设备的列表
显示
<service android:name=".ManagerService" android:enabled="true" />
<receiver
android:name=".BootFinishedReceiver"
android:directBootAware="true"
android:enabled="true"
android:exported="false"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
接收器
public class BootFinishedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, ManagerService.class);
context.startService(serviceIntent);
}
}
服务
public class ManagerService extends Service {
private static List<BluetoothDevice> connectedDevices;
@Override
public void onCreate() {
connectedDevices = new ArrayList<BluetoothDevice>();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(connectionReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
unregisterReceiver(connectionReceiver);
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
connectedDevices.add(device);
}else{
connectedDevices.remove(device);
}
}
};
public static List<BluetoothDevice> getConnectedDevices() {
return connectedDevices;
}
}
由于3.1应用程序在活动开始之前无法再接收系统意图,因此也无法使用。
有没有其他方法或如何在以后的android版本中实现它?
谢谢你的建议
嗯,我发现你仍然可以使用ON_BOOT_COMPLETED,但是你必须允许它在你的设备上设置。所以我的问题解决了