Android BLE数据接收问题

时间:2018-08-01 19:28:33

标签: android bluetooth-lowenergy android-ble

我正在为标题写一个android BLE应用程序,但是当我从发现的设备列表(嵌入式设备)中选择一个设备时,该应用程序会连接但没有数据显示...除非再次选择它时间。我知道它是第一次连接,因为该设备有一个LED指示灯,但是直到再次选择它之前,没有数据通过。有谁知道为什么会这样?

public class BluetoothDiscovery extends AppCompatActivity {

private String DEVICE = "Bluetooth Device";
private String COMMS = "Bluetooth Communication";
private int REQUEST_ENABLE_BT = 5;

private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScannerCompat scanner;
private ScanSettings settings;
private UUID baseUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // service UUID
private UUID txUUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // TX UUID characteristic
private UUID rxUUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // RX UUID characteristic
private ScanFilter scanFilter;
private BluetoothDevice device, mdevice;
private BluetoothGatt mGatt;
private boolean mScanning = false;
private ArrayList<deviceShowFormat> foundDevices = new ArrayList<>();
formattingAdapter BTadapter;

Button scanButton;
TextView fancyWords;
ListView deviceList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_discovery);

    BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = manager.getAdapter();

    //mBluetoothAdapter.getBluetoothLeScanner();
    //mBluetoothAdapter.getDefaultAdapter();//.getBluetoothLeScanner();

    scanButton = findViewById(R.id.scanButt);
    scanButton.setText(getString(R.string.notScanning));

    fancyWords = findViewById(R.id.discoverText);
    fancyWords.setText(getString(R.string.nonScanTitle));

    deviceList = findViewById(R.id.deviceList);
    BTadapter = new formattingAdapter(BluetoothDiscovery.this, foundDevices);
    deviceList.setAdapter(BTadapter);


    scanner = BluetoothLeScannerCompat.getScanner();

    settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).setReportDelay(1000).build();

    scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(baseUUID)).build();

    //scanner.startScan(Arrays.asList(scanFilter), settings, mScanCallback);

    deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            scanner.stopScan(mScanCallback);
            scanButton.setText(getString(R.string.notScanning));

            deviceShowFormat mBTDevice = foundDevices.get(i);

            BluetoothDevice Device = mBTDevice.get_device();
            String deviceName = mBTDevice.get_device_name();
            String deviceAddress = mBTDevice.get_device_address();

            Log.i(DEVICE, "Selected device: " + Device.toString());
            Log.i(DEVICE, "Selected device name: " + deviceName);
            Log.i(DEVICE, "Selected device address: " + deviceAddress);


            mBluetoothAdapter.getRemoteDevice(deviceAddress);
            mGatt = Device.connectGatt(BluetoothDiscovery.this, false, mGattCallback);

        }
    });
}

private final no.nordicsemi.android.support.v18.scanner.ScanCallback mScanCallback = new no.nordicsemi.android.support.v18.scanner.ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);

        Log.i("onScanResult", "device detected");

        device = result.getDevice();
        String deviceName = device.getName();
        String deviceAddress = device.getAddress();

        Log.i(DEVICE, "Scanned device: " + device.toString());
        Log.i(DEVICE, "Scanned device name: " + deviceName);
        Log.i(DEVICE, "Scanned device address: " + deviceAddress);


        foundDevices.add(new deviceShowFormat(device, deviceName, deviceAddress));
        BTadapter.notifyDataSetChanged();

    }
};

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);

        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED){ // 2
            //Toast.makeText(BluetoothDiscovery.this, "Attempting service discovery", Toast.LENGTH_SHORT).show();
            //Log.i("onConnectionStateChange", "Attempting service discovery: " + mGatt.discoverServices());
            gatt.discoverServices();

        } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED){ // 0
            Toast.makeText(BluetoothDiscovery.this, "Connection has been terminated?", Toast.LENGTH_SHORT).show();

        } else if (status != BluetoothGatt.GATT_SUCCESS){
            Log.i("GATT", "Unsuccessful");
            gatt.disconnect();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status){
        super.onServicesDiscovered(gatt, status);

        Log.i("onServicesDiscovered", "Hey, we found a service");

        List<BluetoothGattService> services = gatt.getServices();
        Log.i("SERVICE", "Services: " + services.toString());


        BluetoothGattCharacteristic characteristic = services.get(4).getCharacteristics().get(0);
        //BluetoothGattCharacteristic characteristic = gatt.getService(baseUUID).getCharacteristic(rxUUID);


        gatt.setCharacteristicNotification(characteristic, true);



        List<BluetoothGattDescriptor> describeMe = characteristic.getDescriptors();
        Log.i("DESCRIPTORS", "Descriptors: " + describeMe.toString());
        Log.i("DESCRIPTORS", "Descriptors: " + describeMe.get(1).getUuid().toString());


        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(describeMe.get(0).getUuid());//UUID.fromString("00002902-0000-1000-8000-00805F9B34FB"));//describeMe.get(1).getUuid()
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        gatt.writeDescriptor(descriptor);

        Log.i("ByeSERVICESDISCOVERED", "that");
    }


    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        Log.i("onCharacteristicChanged", "Entered");

        byte[] dataInput = characteristic.getValue();
        Log.i("MESSAGE", dataInput.toString());

        try {
            String data = new String(dataInput, "UTF-8");

            // create list to contain data

            Log.i("MESSAGE2", data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        Log.i("onCharacteristicChanged", "Bye");
    }

};

public void toggleScan(View view){
    mScanning = !mScanning;

    if(mScanning){
        scanner.startScan(mScanCallback); //Arrays.asList(scanFilter) null, settings,
        scanButton.setText(getString(R.string.scanInProgress));
        fancyWords.setText(getString(R.string.ScanTitle));

    } else {
        scanner.stopScan(mScanCallback);
        scanButton.setText(getString(R.string.notScanning));
        //foundDevices.clear();
    }
}



}

编辑:登录首次点击enter image description here

登录第二次单击enter image description here

红色标记我的调试日志

0 个答案:

没有答案