简体   繁体   English

Android BLE设备发现,连接和断开连接

[英]Android BLE device discover, connect & disconnect

Basically, I am an iOS developer. 基本上,我是iOS开发人员。 I have a requirement to scan, connect & disconnect BLE devices. 我需要扫描,连接和断开BLE设备。 Everything works fine in iOS. 在iOS中一切正常。 Then I tried the following code to scan in Android. 然后,我尝试了以下代码在Android中进行扫描。 None of the devices re scanned at anytime. 任何时候都不会重新扫描任何设备。 Could anyone help me, if I am doing something wrong. 如果我做错了什么,谁能帮助我。

public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
TextView statusTextView;

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

    statusTextView = (TextView)findViewById(R.id.statusTxtView);
}

@Override
protected void onStart() {
    super.onStart();

    enableBluetooth();
}

private void enableBluetooth() {
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        statusTextView.setText("BT disabled");
        Intent enableBtIntent =
                new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    } else {
        statusTextView.setText("BT enabled");
    }

    boolean status = bluetoothAdapter.startDiscovery();

    if (status == true) {
        statusTextView.setText("Start scanning");
    } else {
        statusTextView.setText("Failed scanning");
    }
}

BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        statusTextView.setText(device.getName());
    }
};

} }

You've not started scanning. 您尚未开始扫描。 After starting bluetooth discovery using bluetoothAdapter.startDiscovery() , you have to start scanning in order to get scan results. 使用bluetoothAdapter.startDiscovery()启动蓝牙发现后,必须开始扫描才能获取扫描结果。 Use the following code to start scan. 使用以下代码开始扫描。

I've not tested it but it should work as follows: 我尚未对其进行测试,但它应如下工作:

BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
scanner.startScan(scanCallback);

where scanCallback is the above callback you have created but unused. 其中scanCallback是您已创建但未使用的上述回调。

Make sure that you have BLUETOOTH_ADMIN permission. 确保您具有BLUETOOTH_ADMIN权限。

First you have to scan device 首先,您必须扫描设备

@SuppressLint("NewApi")
private void turnonBLE() {
    // TODO Auto-generated method stub
    manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    mBLEAdapter = manager.getAdapter();
    mLeScanner = mBLEAdapter.getBluetoothLeScanner();

    mBLEAdapter.enable();
    scanLeDevice(true);
    Toast.makeText(getApplicationContext(), "BTLE ON Service",
            Toast.LENGTH_LONG).show();
    Log.e("BLE_Scanner", "TurnOnBLE");
}

If you are not using any uuid then scan without uuid 如果您不使用任何uuid,则不使用uuid进行扫描

public void scanLeDevice(final boolean enable) {
    if (enable) {

        if (Build.VERSION.SDK_INT < 21) {
            mBLEAdapter.startLeScan(mLeScanCallback);
        } else {
            ParcelUuid uuid = ParcelUuid.fromString(UUIDList.SENSOR_MAIN_SERVICE_UUID_STRING.toString());
            ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(uuid).build();
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .setReportDelay(0)
                    .build();

            if (mLeScanner != null)
                mLeScanner.startScan(Collections.singletonList(scanFilter), settings, mScanCallback);
        }
    } else {
        if (Build.VERSION.SDK_INT < 21) {
            mBLEAdapter.stopLeScan(mLeScanCallback);
        } else {
            mLeScanner.stopScan(mScanCallback);
        }
    }
}

From that call scanCallback 从该呼叫scanCallback

private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        BluetoothDevice btDevice = result.getDevice();
        connectToDevice(btDevice, result.getScanRecord().getBytes());
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        for (ScanResult sr : results) {
            Log.e("ScanResult - Results", sr.toString());
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("Scan Failed", "Error Code: " + errorCode);

    }
};

for connect device call gattCallback 用于连接设备调用gattCallback

private synchronized void connectToDevice(BluetoothDevice device, byte[] scanRecord) {
    mGatt = device.connectGatt(getApplicationContext(), false, mBtGattCallback);
 }

private BluetoothGattCallback mBtGattCallback = new BluetoothGattCallback() {
    // override all methods
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM