2017-09-05 4 views
0

BLE 장치에 메시지를 보내려고합니다. 필자가 이해할 수 있도록 처음에는 장치 서비스를 발견하고 메시지를 서비스 특성으로 보내야합니다.BLE 서비스가 발견되지 않음

public class BluetoothLeService extends Service { 

private BluetoothManager mBluetoothManager; 
private BluetoothAdapter mBluetoothAdapter; 
private String mBluetoothDeviceAddress; 
private BluetoothGatt mBluetoothGatt; 

private String macAddress; 
private String serviceUuid; 
private String characteristicUuid; 
private Application app; 
private int transmissionValue = 450;  

public BluetoothLeService(String address, String serviceUuid, String characteristicUuid) { 
    this.macAddress = address; 
    this.serviceUuid = serviceUuid; 
    this.characteristicUuid = characteristicUuid; 
} 


private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { 
    @Override 
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 
     System.out.println("connectionStateChange: " + status); 
     if (STATE_CONNECTED == newState) { 
      gatt.discoverServices(); 
     } 
    } 

    @Override 
    public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
     if(gatt.getDevice().getName().equals("MyDeviceName")) { 
      sendMessageAfterDiscovery(gatt); 
     } 
    } 

}; 

public boolean initialize(Application app) { 
    this.app = app; 
    if (mBluetoothManager == null) { 
     mBluetoothManager = (BluetoothManager) app.getSystemService(Context.BLUETOOTH_SERVICE); 
     if (mBluetoothManager == null) { 
      return false; 
     } 
    } 

    mBluetoothAdapter = mBluetoothManager.getAdapter(); 
    if (mBluetoothAdapter == null) { 
     return false; 
    } 
    return true; 
} 


public boolean connect() { 
    return connect(macAddress); 
} 

public boolean connect(final String address) { 
    this.macAddress = address; 
    if (mBluetoothAdapter == null || macAddress == null) { 
     return false; 
    } 

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress); 
    if (device == null) { 
     Log.w(TAG, "Device not found. Unable to connect."); 
     return false; 
    } 
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback); 
    return true; 
} 

public void writeCharacteristic(int value) { 
    this.transmissionValue = value; 
    BluetoothDevice mDevice = mBluetoothAdapter.getRemoteDevice(this.macAddress); 
    BluetoothGatt mBG = mDevice.connectGatt(app.getApplicationContext(), true, mGattCallback); 
    System.out.println("device name: " + mBG.getDevice().getName()); 

} 

private void sendMessageAfterDiscovery(BluetoothGatt gatt) { 
    BluetoothGattService mSVC = gatt.getService(UUID.fromString(serviceUuid)); 

    BluetoothGattCharacteristic mCH = mSVC.getCharacteristic(UUID.fromString(characteristicUuid)); 
    mCH.setValue(transmissionValue, BluetoothGattCharacteristic.FORMAT_UINT16, 0); 
    System.out.println("characteristic writable: " + isCharacteristicWriteable(mCH)); 

    System.out.println("success? " + gatt.writeCharacteristic(mCH)); 
} 

public static boolean isCharacteristicWriteable(BluetoothGattCharacteristic pChar) { 
    return (pChar.getProperties() & (BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != 0; 
} 

}

그리고 여기에 내가 메시지를 보낼 코드입니다 : 그래서 여기에 내가 무슨 짓을 내가 장치에 연결하고 보낼 때마다 지금

private void sendMessage() { 
    BluetoothLeService ble = new BluetoothLeService("B0:00:00:00:00:C0", "0000fff0-1111-0000-0000-00805f9b34fb","0000fff1-1111-0000-0000-00805f9b34fb"); 
    ble.initialize(app); 
    ble.connect();, 
    ble.writeCharacteristic(450) 
} 

을 장치의 이름을 얻을 수 있기 때문에 장치가 인식 되더라도 onServiceDiscovered 메서드는 호출되지 않습니다. 또한 오류가 발생하지 않습니다.

왜이 메서드는 호출되지 않습니까? 내가 뭔가 잘못하고 있는거야? 이미 사용 권한을 확인했으며 클래스를 매니페스트의 서비스로 추가했습니다. 당신의 도움에 대한

덕분에 ...

답변

1

당신은 당신의 GATT 콜백의 onConnectionStateChange 방법 내에서 discoverServices를 호출해야합니다. discoverServices 방법 문서 : 원격 장치뿐만 아니라 특성 기술자가 제공

발견 서비스.

이것은 비동기 작업입니다. 서비스 검색이 완료되면 onServicesDiscovered(BluetoothGatt, int) 콜백은 이 트리거됩니다. 검색이 성공한 경우 원격 서비스는 getServices() 기능을 사용하여 검색 한 일 수 있습니다. 귀하의 경우에는

, 당신의 코드를 업데이트하는 트릭해야 다음과 같이 : 난 그냥 그 시도

@Override 
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 
    System.out.println("connectionStateChange: " + status); 

    if (STATE_CONNECTED == newState) { 
     gatt.discoverServices(); 
    } 
} 
+0

을; 하지만 onConnectionStateChange에서이 메서드를 호출하면이 메서드는 호출되지 않지만 여전히 connectGatt 뒤에 deviceName이 나타납니다. 코드를 업데이트했습니다. –

+0

연결 상태가 'STATE_CONNECTED'(으)로 되돌아 오는 것을 확인 했습니까? – stkent

+0

onConnectionStateChange는 호출되지 않습니다. 그래서 확인할 연결 상태가 없습니다. –

관련 문제