1 回答
TA贡献1825条经验 获得超6个赞
解决了!
只需将 BroadcastReceiver 分成两部分即可。请不要在不了解会发生什么的情况下复制此答案。此代码会消耗大量电池电量。我的项目允许这样做。它将具有类似于连续电源的功能。它仅在某些条件下运行。干杯!
private final BroadcastReceiver broadcastReceiver1=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
if(deviceFound==false) {
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.startDiscovery();
}
};
}
};
private final BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName=device.getName();
String deviceHardwareAddress=device.getAddress();
int rssi=intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
if(deviceHardwareAddress.equals(MAC)){
deviceFound=true;
bluetoothAdapter.cancelDiscovery();
Log.i("broadcastReceiver" , "device " + deviceName);
Log.i("broadcastReceiver" , "hard" + deviceHardwareAddress);
Log.i("broadcastReceiver","Rssi "+rssi);
Log.i("broadcastReceiver","Paired Id "+MAC );
tv.setText(deviceName+" "+rssi);
deviceFound=false;
bluetoothAdapter.startDiscovery();
}
}
}
};
添加回答
举报