在你的仙女座宣言中加入蓝牙许可,
然后使用意图筛选器侦听ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECT_REQUESTED,和ACTION_ACL_DISCONNECTED广播:publicvoidonCreate(){
...
IntentFilterfilter=newIntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver,filter);}//TheBroadcastReceiverthatlistensforbluetoothbroadcastsprivatefinal
BroadcastReceivermReceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(BluetoothDevice.ACTION_FOUND.equals(action)){
...//Devicefound
}
elseif(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
...//Deviceisnowconnected
}
elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
...//Donesearching
}
elseif(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)){
...//Deviceisabouttodisconnect
}
elseif(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
...//Devicehasdisconnected
}
}};
几个注意事项:无法在应用程序启动时检索已连接设备的列表。蓝牙API不允许您查询,而是允许您侦听更改。
解决上述问题的一个棘手的工作就是检索所有已知/配对设备的列表.然后尝试连接到每一个(以确定您是否已连接)。
或者,您可以让后台服务监视蓝牙API,并将设备状态写入磁盘,以便应用程序稍后使用。