detect bluetooth Le devices in Android

后端 未结 4 2041
一向
一向 2021-02-06 07:24

I\'m a beginner in android app development. I\'ve tried reading the documentation but am getting nowhere (functions in Android\'s tutorial such as StartLeScan() hav

4条回答
  •  广开言路
    2021-02-06 07:37

    basically it depends on which android version you are targeting. since the api has changed a bit in lollipop (21).

    in your activity, get the bluetooth adapter

    BluetoothManager bm = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)
    BluetoothAdapter mBluetoothAdapter = bm.getAdapter();
    
    // Ensures Bluetooth is available on the device and it is enabled. If not, 
    // displays a dialog requesting user permission to enable Bluetooth. 
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { 
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
    

    then you should check which android version you are targeting

    int apiVersion = android.os.Build.VERSION.SDK_INT;
    if (apiVersion > android.os.Build.VERSION_CODES.KITKAT){
     BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
     // scan for devices
     scanner.startScan(new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                // get the discovered device as you wish
                // this will trigger each time a new device is found
    
                BluetoothDevice device = result.getDevice();
            }
        });
    } else {
        // targetting kitkat or bellow
        mBluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                // get the discovered device as you wish
    
            }
        });
    
    // rest of your code that will run **before** callback is triggered since it's asynchronous
    

    dont forget to add permissions in your manifest

        
        
    

提交回复
热议问题