如何在android中扫描范围内可用的蓝牙设备?

发布于 2024-09-08 01:57:27 字数 166 浏览 5 评论 0原文

我需要使用 google android 2.1 获取该地区可用蓝牙设备的列表。

问题是,我不仅需要这些设备的列表,我还需要为找到的每个设备提供一些唯一的 ID,并且我需要一个指示器,指示接收到的信号有多“好”(例如 android.wifi.ScanResult 中的“级别”) )...我该怎么做?

I need to get a list of available bluetooth devices in the area using google android 2.1.

Thing is, i don't just need a list of those devices, i need some unique id for each device found and i need an indicator, how "good" the signal is received (like the "level" in android.wifi.ScanResult)... How do i do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

撩心不撩汉 2024-09-15 01:57:27

查看下面的代码:

开始搜索

mBluetoothAdapter.startDiscovery(); 
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    //Finding devices                 
    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // Add the name and address to an array adapter to show in a ListView
       mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
  }
};

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter);

Check out code below :

Starting search

mBluetoothAdapter.startDiscovery(); 
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    //Finding devices                 
    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // Add the name and address to an array adapter to show in a ListView
       mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
  }
};

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter);
晨与橙与城 2024-09-15 01:57:27

调用方法 bluetoothScanning,需要上下文

void bluetoothScanning(){

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    context.registerReceiver(mReceiver, filter);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothAdapter.startDiscovery();

}


// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address

            Log.i("Device Name: " , "device " + deviceName);
            Log.i("deviceHardwareAddress " , "hard"  + deviceHardwareAddress);
        }
    }
};

结果

名称:LE-Bose Revolve+ SoundLink
设备硬件地址:MAC .....

Call method bluetoothScanning, context is required

void bluetoothScanning(){

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    context.registerReceiver(mReceiver, filter);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothAdapter.startDiscovery();

}


// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address

            Log.i("Device Name: " , "device " + deviceName);
            Log.i("deviceHardwareAddress " , "hard"  + deviceHardwareAddress);
        }
    }
};

Result

Name: LE-Bose Revolve+ SoundLink
deviceHardwareAddress: MAC .....

心如荒岛 2024-09-15 01:57:27

此代码使用 BeaconManager,它不断扫描新的蓝牙设备并返回一个信标列表对象,您可以使用该对象来获取所需的信息。

确保导入 BeaconManager

private BeaconManager beaconManager;

//In onCreate method
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));

//use these out of the onCreate method
public void onScanStart(View view) {
        stopScanButton.setEnabled(true);
        scanningButton.setEnabled(false);
        beaconManager.bind(this);
}

@Override
public void onBeaconServiceConnect() {
    beaconManager.removeAllRangeNotifiers();
    beaconManager.addRangeNotifier(new RangeNotifier() {
    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
    for (Beacon b : beacons) {
        System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi()));
  });
    try {
//Tells the BeaconService to start looking for beacons that match the passed.
        beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
    } catch (RemoteException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
}

让我知道这是否适合您!

This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.

Make sure you import BeaconManager

private BeaconManager beaconManager;

//In onCreate method
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));

//use these out of the onCreate method
public void onScanStart(View view) {
        stopScanButton.setEnabled(true);
        scanningButton.setEnabled(false);
        beaconManager.bind(this);
}

@Override
public void onBeaconServiceConnect() {
    beaconManager.removeAllRangeNotifiers();
    beaconManager.addRangeNotifier(new RangeNotifier() {
    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
    for (Beacon b : beacons) {
        System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi()));
  });
    try {
//Tells the BeaconService to start looking for beacons that match the passed.
        beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
    } catch (RemoteException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
}

Let me know if that works for you!

朦胧时间 2024-09-15 01:57:27

能够通过蓝牙发现设备。确保

AndroidManifest.xml

<uses-permission
    android:name="android.permission.BLUETOOTH"
    android:maxSdkVersion="30" />
<uses-permission
    android:name="android.permission.BLUETOOTH_ADMIN"
    android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

MainActivity

class MainActivity : AppCompatActivity() {

    private var bluetoothAdapter: BluetoothAdapter? = null
    private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            Log.i("TAG", "onReceive $action")
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                Log.i("TAG", "Discovery finished, hide loading")
            } else if (BluetoothDevice.ACTION_FOUND == action) {
                val device =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                Log.i("TAG", "Device Name: " + (device?.name ?: ""))
                Log.i("TAG", "Device Address:" + (device?.address ?: ""))
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        findViewById<Button>(R.id.button_start_discovery).setOnClickListener {
            if (bluetoothAdapter == null) {
                initBluetoothDiscovery()
            }
            startDiscovery()
        }
    }

    private fun initBluetoothDiscovery() {
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
        val intentFilter = IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        }
        registerReceiver(bluetoothReceiver, intentFilter)
    }

    private fun startDiscovery() {
        if (bluetoothAdapter?.isDiscovering == true) {
            Log.i("TAG", "cancel start discovery")
            bluetoothAdapter?.cancelDiscovery()
        }
        Log.i("TAG", "start discovery, show loading")
        bluetoothAdapter?.startDiscovery()
    }

    override fun onDestroy() {
        super.onDestroy()
        bluetoothAdapter?.cancelDiscovery();
        unregisterReceiver(bluetoothReceiver);
    }
}

To able to discovery devices by bluetooth. Make sure you

AndroidManifest.xml

<uses-permission
    android:name="android.permission.BLUETOOTH"
    android:maxSdkVersion="30" />
<uses-permission
    android:name="android.permission.BLUETOOTH_ADMIN"
    android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

MainActivity

class MainActivity : AppCompatActivity() {

    private var bluetoothAdapter: BluetoothAdapter? = null
    private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            Log.i("TAG", "onReceive $action")
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                Log.i("TAG", "Discovery finished, hide loading")
            } else if (BluetoothDevice.ACTION_FOUND == action) {
                val device =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                Log.i("TAG", "Device Name: " + (device?.name ?: ""))
                Log.i("TAG", "Device Address:" + (device?.address ?: ""))
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        findViewById<Button>(R.id.button_start_discovery).setOnClickListener {
            if (bluetoothAdapter == null) {
                initBluetoothDiscovery()
            }
            startDiscovery()
        }
    }

    private fun initBluetoothDiscovery() {
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
        val intentFilter = IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        }
        registerReceiver(bluetoothReceiver, intentFilter)
    }

    private fun startDiscovery() {
        if (bluetoothAdapter?.isDiscovering == true) {
            Log.i("TAG", "cancel start discovery")
            bluetoothAdapter?.cancelDiscovery()
        }
        Log.i("TAG", "start discovery, show loading")
        bluetoothAdapter?.startDiscovery()
    }

    override fun onDestroy() {
        super.onDestroy()
        bluetoothAdapter?.cancelDiscovery();
        unregisterReceiver(bluetoothReceiver);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文