简体   繁体   中英

Android BLE device discover, connect & disconnect

Basically, I am an iOS developer. I have a requirement to scan, connect & disconnect BLE devices. Everything works fine in iOS. Then I tried the following code to scan in 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. 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.

Make sure that you have BLUETOOTH_ADMIN permission.

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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