簡體   English   中英

Android BLE設備發現,連接和斷開連接

[英]Android BLE device discover, connect & disconnect

基本上,我是iOS開發人員。 我需要掃描,連接和斷開BLE設備。 在iOS中一切正常。 然后,我嘗試了以下代碼在Android中進行掃描。 任何時候都不會重新掃描任何設備。 如果我做錯了什么,誰能幫助我。

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());
    }
};

}

您尚未開始掃描。 使用bluetoothAdapter.startDiscovery()啟動藍牙發現后,必須開始掃描才能獲取掃描結果。 使用以下代碼開始掃描。

我尚未對其進行測試,但它應如下工作:

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

其中scanCallback是您已創建但未使用的上述回調。

確保您具有BLUETOOTH_ADMIN權限。

首先,您必須掃描設備

@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");
}

如果您不使用任何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);
        }
    }
}

從該呼叫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);

    }
};

用於連接設備調用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