我尝试在android中使用BluetoothGatt API以编程方式与Ble iBeacon配对。我能够与Ble iBeacon配对到棒棒糖。但是我不能在Marshmallow配对(我的测试设备是oneplus 3)。我&# 39; m使用altbeacon库进行信标扫描。
此外,我在清单文件中提供了ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION权限并打开了GPS位置。
private BluetoothGatt mGatt;
BluetoothAdapter baBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
baBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(myReceiver, intentFilter);
}
这里我发送beacon mac id
public void PairToDevice(String sMacId) {
BluetoothDevice device = baBluetoothAdapter.getRemoteDevice(sMacId);
if (mGatt == null) {
mGatt = device.connectGatt(this, false, gattCallback);
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i("onConnectionStateChange", "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.e("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
}
}
这里我正在检查粘合状态。在棉花糖中,粘合状态总是没有。但是在棉花糖的情况下,它的工作正常。
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int nState = device.getBondState();
if (nState == BluetoothDevice.BOND_BONDED) {
Log.e("Bond Information", "device bonded");
} else if (nState == BluetoothDevice.BOND_BONDING) {
Log.e("Bond Information", "device bonding");
} else if (nState == BluetoothDevice.BOND_NONE) {
Log.e("Bond Information", "bond none");
}
}
}
};